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 !
The callback is a function that's accepted as an argument and executed by another function (the higher-order function). There are 2 kinds of callback functions: synchronous and asynchronous. The synchronous callbacks are executed at the same time as the higher-order function that uses the callback.
The only way to make something asynchronous was to use a host-provided function, such as nextTick (or any of the various operations that completes asynchronously) on NodeJS or setTimeout on browsers.
Using callbacks, we can begin to separate – with a callback, we can load the data and, when the asynchronous operation is done, run the callback function. It does keep them nicely separated and it does pass the data into the callback as a parameter.
Callbacks can help you prevent overfitting, visualize training progress, debug your code, save checkpoints, generate logs, create a TensorBoard, etc. There are many callbacks readily available in TensorFlow, and you can use multiple.
this is easy
var callback = (function(){
var finishedCalls = 0;
return function(){
if (++finishedCalls == 4){
//execute your action here
}
};
})();
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
function createCallback(limit, fn){
var finishedCalls = 0;
return function(){
if (++finishedCalls == limit){
fn();
}
};
}
var callback = createCallback(4, function(){
alert("woot!");
});
async1(callback);
async2(callback);
async3(callback);
async4(callback);
I've written some async utilities you might find useful, allowing you to write your example as:
function(callback) {
async.series([
asynch1(),
asynch2(),
...
asynchN()
], callback);
}
Or, if you wanted to run them in parallel, as:
function(callback) {
async.parallel([
asynch1(),
asynch2(),
...
asynchN()
], callback);
}
There are loads of other useful functions like async map/reduce too:
http://caolanmcmahon.com/async.html
Hope that helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With