0

Say I have two (or more) asynchronous operations op1 and op2 that call a callback function upon completion. How do I best wait for both to complete before starting op3?
I am not able to nest them inside of each other (i.e. first starting op1, then starting op2 inside of op1callback())
(I of course also do not know which of these is going to complete first, but that doesn't really matter I guess)

function op1callback {
}
function op2callback {
}
function op3 {
...
}
lux
  • 139
  • 2
  • 8

1 Answers1

1

The easiest would be to just keep flags about the callbacks state:

let count = 0;

function callback() {
  if(++count === 2) op3();
}

op1(callback); op2(callback);

But in the long term it might be beneficial to let the operations return promises, e.g.:

 async function op1() { 
   // Do some async stuff and *await* that
   return "something";
 }

then you could just do:

 Promise.all(op1(), op2()).then(op3);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151