Suppose I use Node.js to try to run two async calls to get some answers. I know there's an async package, where you can just pass two functions, and an optional callback.
async.parallel([fun1(){callback(null,1);},
fun2(){callback(null,2);}],
function(err, results) {
});
But suppose I have a priority now, if fun1 returns a value, then I do not need fun2's answer, only if fun1 returns null, then I wait for fun2. So I don't want to use the callback function, because the callback waits for both functions to finish, and fun2 may take very long.
Right now I just use a very exhaustive way by creating a callback function for both async calls.
function(){
var theAnswer,FromFun1,FromFun2;
var reply1,reply2;
fun1(reply1="answered";FromFun1=1;complete());
fun2(reply2="answered";FromFun2=2;complete());
function complete(answer){
if(reply1=="answered"){
theAnswer=FromFun1;
}else if(reply1==null){
// Don't do anything because fun1 is not finished running.
}else if(reply2=="answered"){
theAnswer=FromFun2;
}else{
// Both have no answer, err.
}
}
}
Is there a better way to do this?
The trick I've used for this scenario is to return "done" in first argument of the callback:
async.parallel([
function(callback){
callback("done",1);
},
function(callback){
callback(null,2);
}
], function(err, results) {
console.log(err, results); // done [ 1 ] or done [ 1 , 2 ]
});
Sounds like a hack and I don't usually do it but in some rare cases like this one, it actually keeps the code clean... just document it so that others know what you intention is.
Its better to use waterfall instead of parallel execution coz you can pass the result form your previous function to next one as argument.
async.waterfall([
function(callback){
callback(null, 'one');
},
function(arg1, callback){
// arg1 now equals 'one'
if(arg1==null){
// it will not take time it returns immediately
callback(null, 'done');
}else{
// do your another stuff here fun2 logic here
// it will not be executed and so it dont take time
}
}
], function (err, result) {
// result now equals 'done'
});
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