Wait for one function to finish before continuing?
The issue is that making a function async
doesn't make it automatically wait for anything asynchronous going on inside it
async
/await
is syntax "sugar" for working with Promises, and Promises only
So, if you use the promise version of writeFile/readFile like so
import * as fs from 'fs/promise';
you can write your code as follows
genPriceChangeScripts: async() => {
const priceScript = `...`;
const changeData = await get24hrChange();
const globalCmds = [];
const globalPol = [];
const filtered = changeData.filter(function (item) {
return (!item.symbol.includes("BTCUSDT_") && !item.symbol.includes("ETHUSDT_"));
});
async function scripts() {
const promises = filtered.map((e) => {
const data = e.symbol;
const change = priceScript.replace("CHANGE", data);
return fs.writeFile(`../scripts/price_change/${data.toLowerCase()}_price_change.sh`, change);
});
await Promise.all(promises);
console.log("scripts finished");
}
await scripts();
async function commands() {
for (let i = 0; i < filtered.length; i++) {
var pushCmds = `"#($CURRENT_DIR/scripts/price_change/${filtered[i].symbol.toLowerCase()}_price_change.sh)"`;
globalCmds.push(pushCmds);
}
const commands = globalCmds.join("\n");
const cmdsWithComment = commands.concat("\n#CHANGE3");
const data = await fs.readFile("../binance.tmux", "utf-8");
const addCmds = data.replace("#CHANGE1", cmdsWithComment);
await fs.writeFile("../binance.tmux", addCmds);
console.log("cmds finished");
}
await commands();
async function pols() {
for (let i = 0; i < filtered.length; i++) {
const pushPol = `"\\#{${filtered[i].symbol.toLowerCase()}_price_change}"`;
globalPol.push(pushPol);
}
const pol = globalPol.join("\n");
const polWithComment = pol.concat("\n#CHANGE4");
const data = await fs.readFile("../binance.tmux", "utf-8");
const addPol = data.replace("#CHANGE2", polWithComment);
await fs.writeFile("../binance.tmux", addPol);
console.log("pols finished");
}
await pols();
return prompt.end();
},
How to wait for function to finish in javascript?
You can just use async/await for your defined functions, even if you cannot use 'await' keyword outside an async function.
So, for example, you have a index.js file, you can do:
async function main() {
await updateSeason();
await updateFixtures();
}
main()
or invoking directly the function with the short form
(async function main() {
await updateSeason();
await updateFixtures();
})()
Anyway, avoid to use 'writeFileSync' or other 'Sync' functions inside an async function because that block the event loop and decrease your performance.
EDIT: I saw now that you are using Array.prototype.map function with an async callback, that could be the problem.
Try to look here: https://flaviocopes.com/javascript-async-await-array-map/
Or, otherwise, use a standard for loop to handle your leagues
Forcing a function to wait until another function is complete
You want to use promises if you have asynchronous code. Promise.all() will wait for them all to be complete before running.
function task1() { return new Promise(function(resolve, reject) { console.log("task 1") setTimeout(function() { resolve('foo'); }, Math.random() * 2000); })}
function task2() { return new Promise(function(resolve, reject) { console.log("task 2") setTimeout(function() { resolve('bar'); }, Math.random() * 2000); })}
function task3() { console.log("task 3")}
Promise.all([task1(), task2()]).then(function(values) { console.log(values); task3()});
javascript wait for function to finish execution before continuing
Javascript is heavily optimised. You need to declare the update() function is asynchronous, and then use a Promise to await the response of the update. Have a look at this example.
JavaScript - wait for a function to finish processing before going to the next iteration of the loop
You will need to convert your loadFileIntoMemory into a Promise.
function loadFileIntoMemory(file) {
return new Promise((resolve,reject) => {
......
reader.onload = function (file) {
......
return resolve(); //when all is done, resolve the promise.
}
})
}
Then you can use the function in a async/await loop.
const processFiles = async (files) => {
for (let i = 0; i < files.length; i++) {
console.log("Loading File into memory");
await loadFileIntoMemory(files[i]);
}
}
Wait till one function finishes before executing the second JS
async / await is not the only solution. And in any case, you are going to need to create a promise in functionOne
/*async*/ function functionOne(){
var s;
var p = new Promise(function(success) {
chrome.storage.local.get(['prm'], function(result) {
s = result.prm;
success(s);
});
}
return p;
}
function functionTwo(){
let p = functionOne();
p.then(function(s) {
//...
});
}
You need to create a promise to be able to return the results of chrome.log.storage. You can make functionOne async or not. It doesn't change anything.
Related Topics
Input Date Format With Dd/Mm/Yyyy in the Input Field
How to Convert Jquery Code to JavaScript
Jquery Validation Code for Not Allowed Only Blank Space in Textbox
React-Router Urls Don't Work When Refreshing or Writing Manually
How to Add Class on Specific Div When Scroll
How to Hide Div When You Scroll to Bottom and Show It Again When Scroll Up to Top
How to Read a Properties File in JavaScript from Project Directory
How to Add a New Object (Key-Value Pair) to an Array in JavaScript
Make an Angular *Ngfor Draw Two Different Columns of Data
How to Reload a Page With React-Router
How to Use Js to Open an HTML Select to Show Its Option List
Prevent a White Space in the Beginning of a Input
Random Numbers Between 1 and 50; 50 Times
How to Clear Browsing History Using JavaScript
Check If a String Has White Space