I need to execute a bunch of asynchronous methods (client SQLite database), and call only one final callback.
Of course, the ugly way is:
execAll : function(callBack) {
asynch1(function() {
asynch2(function() {
...
asynchN(function() {
callBack();
})
})
});
}
But I know there are better ways to do it. Intuitively I would detect when all call back has been called with a counter to call the final callback.
I think this is a common design-pattern, so if someone could point me in the right direction...
Thanks in advance !
Promises can help manage this. There are two general scenarios - parallel and serial. Parallel can be accomplished using Promise.all(), serial is more complex - task B can only start when task A is done. Here's a bare-bones sample:
You may need some ES6/7 translation to make this work in browsers or older node versions.
You should consider using Deferred pattern for asynchronous methods. You can get more information from the this StackOverflow question and answers:
What are the differences between Deferred, Promise and Future in JavaScript?
The marked answer from jnewman was good actually!
Hope this helps.
this is easy
Just pass this callback to all your methods, and once it has been called 4 times it will execute.
If you want to use factory for this then you can do the following
I've written some async utilities you might find useful, allowing you to write your example as:
Or, if you wanted to run them in parallel, as:
There are loads of other useful functions like async map/reduce too:
http://caolanmcmahon.com/async.html
Hope that helps!