1

I have two functions that do asynchronous things. When they have finished, I want to execute the rest of my code.

Of course if I do this:

myFuncA();
myFuncB();
// rest of my code

The rest is executed even if they didn't ended.

I tried this:

var a = false;
var b = false;

a = myFuncA(); // return true when it ends
b = myFuncB(); // return true when it ends

while (!a && !b) {
  // just waiting the two functions to end
}
// rest of my code

I expected the loop to end when the two functions end, but it doesn't work.

So I tried almost the same but with global variables:

var a = false;
var b = false;

myFuncA(); // value a = true when it ends
myFuncB(); // value b = true true when it ends

while (!a && !b) {
  // just waiting the two functions to end
}
// rest of my code

But it doesn't work either.

So my question is: what is the method for waiting for the results of async functions to continue the code execution?

Destal
  • 189
  • 3
  • 11
  • 2
    Have you tried Promises? – Mazz Mar 13 '17 at 11:28
  • 1
    Also async await could help you! – funcoding Mar 13 '17 at 11:30
  • You can use jQuery Deferred and $.when. – Zapo Mar 13 '17 at 11:36
  • Why do people always feel the need to suggest libraries and frameworks when this is a simple logical problem that can be resolved by simply using a callback. @Simon Déchamps if you read this before you look at all these links, I suggest you can solve your problem easily by putting the rest of your code in a function C. Then in function A, you set a to True at the end, and check if b is also true, if yes, you trigger C(). In your function B, you set b to true at the end, and check if a is also true, if yes, you trigger C(). It will that way only execute once both have finished. Simple. – zoubida13 Mar 13 '17 at 11:37
  • Thank you guys, I'll check that. @zoubida13 you are right, I could even execute B in A callback, then C in B callback, or even have A, B and C code in only one function and falling from callback to callback since these functions are not made to be reused elsewhere. But I wanted my code to be more clear by splitting that big function into three (A and B are already handling callbacks in callbacks because of loops on HTTP requests and SQLite requests, so it's starting to make many callbacks). But your solution could be a good compromise. – Destal Mar 13 '17 at 13:13
  • @zoubida13 It's not so simple any more if you need to add error handling. Promises are neither a library nor a framework btw, they are the standardised solution to this problem. – Bergi Mar 13 '17 at 13:15

0 Answers0