Pages

How to get output of multiple asynchronous calls in one callback


Javascript IO is asynchronous, which is awesome but sometime you might land into a situation where you wanted to call several asynchronous function and when all of them are ready you have to perform some action. Obviously you can not nest each other with anonymous functions in all situations.

so intead of doing this (assume u need to call several asyncCalls 1,2,3 etc,)


         asyncCall1(param1,function (output1){
           asyncCall2(param2,function(output2){
              asyncCall3(....)
           })
         })



You might like to do this

    function finalCallback(alloutput){
       //here is your final output
    }
    cbGenerator=getGroupCallBackGenerator(timeout,finalcallback);
    asyncCall1(param1,cbGenerator.getCallback('asyncCall1'))
    asyncCall2(param2,cbGenerator.getCallback('asyncCall2'))
    asyncCall3(param3,cbGenerator.getCallback('asyncCall3'))
    asyncCall4(param4,cbGenerator.getCallback('asyncCall4'))
    cbGenerator.start();



Well You can do it if you want to use my utility function here.


No comments:

Post a Comment

Your comment will inspire me, Please leave your comment