Wait for two async functions to finish then continue in Node.js

Viewed 11543

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?

4 Answers

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});
}

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)
}

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.

Try this:

//using setInterval to wait for completion

//a function which returns a callback
function foo(x,callback){
  //do some computaion on x
  callback(x);
};

//to store the response
let result = [];

//calling foo method twice parallely
foo("123",(data)=>{
  result.push(data);
});

foo("456",(data)=>{
  result.push(data);
});

//waiting till the above functions are done with the execution
//setInterval function will check every 100 ms(can be any value) if the length of the result array is 2
let timer = setInterval(() => {
  if (result.length == 2) {
    clearInterval(timer);
    //prints the two value
    console.log(result.join(""))
  }
}, 100);

Related