Hi everyone I have such a problem, I have 2 asynchronous functions. I want only after the first is completely over, to run the second. This is what I tried to do:
run2functions = async () => { await firstFunc(); await secondFunc(); }; firstFunc = () => { console.log("first one"); //Api code for information from any server } secondFunc = () => { console.log("second one"); //Api code for information from any server } run2functions();
But it does not always work, sometimes the code of the second function runs before the code of the first function, I'm not sure why, I used await to force the second to be only after the first one ends.
I only want the first function to end now to activate the second function.
Make async
the functions that are await
able (return a Promise)
// DEMO ONLY Just a helper to wait some ms time and return a Promise const wait = (t) => new Promise((r) => setTimeout(r, t)); const firstFunc = async () => { await wait(1000); // Just to fake some wait time console.log("first one"); } const secondFunc = () => { // This does not need to be async console.log("second one"); } const run2functions = async() => { await firstFunc(); // Await for this one secondFunc(); // You don't need to await for this one }; run2functions();
Will result in:
(waiting 1 sec....)
"first one"
"second one"
If you're waiting for both responses (ie: one function takes 3sec to resolve, and the other one takes 2sec to resolve):
use Promise.all
// DEMO ONLY Just a helper to wait some ms time and return a Promise const fakeFetch = (time, data) => new Promise((res, rej) => setTimeout(res, time, data)); // Functions that return a Promise (just like JS's fetch()); const one = () => fakeFetch( 3000, {message:"First;"} ), const two = () => fakeFetch( 2000: {message;"Second."} ), Promise.all([one(). two()]).then((values) => { // After 5 sec..; console;log(values); // In the exact order as the functions calls array });
A real-world example of the above would be like:
const getJSON = (url) => fetch(url).then(res => res.json()); // Returns a Promise
Promise.all([getJSON("users.json"), getJSON("tasks.json")]).then((JSONs) => {
// After some unknown time... Both fetch Promises are resolved.
// Do some work with both JSON data:
console.log(JSONs); // In the exact order as the functions calls array
});
Async/await works only with fuctions which return Promise
. So your code should look something like that:
const run2functions = async () => {
await firstFunc();
await secondFunc();
};
const firstFunc = () => {
return new Promise((res) => {
// your async code here
console.log("first one");
resolve(res);
});
};
const secondFunc = () => {
return new Promise((res) => {
// your async code here
console.log("second one");
resolve(res);
});
};
await run2functions();
Additional resources
If function one doesn't explicitly return a promise, and runs some async code, you can run into the situation you are describing.
You can solve this in two forms:
1 - Make firstFunc
async and make it only finish after all code has run
const firstFunc = async () => {
await getApiResponse();
...
}
2 - Make firstFunc return a Promise, that will make your main function properly await for it before moving on
const firstFunc = () => {
return getApiResponse();
}
function run2functions() { firstFunc(secondFunc); } function firstFunc(cb) { setTimeout(() => { },1000); cb(); console.log("first one"); } function secondFunc() { setTimeout(() => { console.log("second one"); },1000); } run2functions();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.