Reputation:
I'm working on an application in Node.js where I'm calling an async function twice, and assign the value to a global variable.
The issue is that I want to use the result of the two calls to do something else, but this something else doesn't wait for the result to be assigned.
Here's my code:
var a;
var b;
let x = 'abcd';
foo(x).then(data=>{
a = data;
});
x = 'efgh';
foo(x).then(data=>{
b = data;
});
console.log(a + b); // for example
How can I wait for the two functions to finish, before executing a + b
?
Upvotes: 8
Views: 15549
Reputation: 2340
As foo
returns a Promise you should mark your function as asyncronus with async
keyword and wait for the foo
function to respond with the await
keyword.
async function someFunction(){
let x = 'abcd';
let a = await foo(x);
x = 'efgh';
let b = await foo(x);
console.log(a + b)
}
Upvotes: 5
Reputation: 1085
Instead of using .then()
you can use await
.
So this:
foo(x).then(data=>{
a = data;
});
would be like this:
a = await foo(x);
Same goes for the other function. This will cause your execution to wait until the functions return.
Notice however that in order to use await
you would have to wrap the statement that uses it, or even better the whole block, in a function that is declared as aync
.You can find more on how to use async
here.
Upvotes: 0
Reputation: 10096
You can use Promise.all
here, to wait for the two promises and then work with their data:
let promises = [];
let x = 'abcd';
promises.push(foo(x))
x = 'efgh';
promises.push(foo(x))
Promise.all(promises).then(([a, b]) => {
console.log(a, b); // for example
});
function foo(d) {
return Promise.resolve({somePaddingData:"", d});
}
Upvotes: 9