Search code examples
javascriptnode.jsasynchronousparallels

Nodejs parallel async call, but with priority


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?


Solution

  • 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.