[removed] execute a bunch of asynchronous method with one callback

前端 未结 4 1494
半阙折子戏
半阙折子戏 2020-12-01 08:21

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 : f         


        
4条回答
  •  春和景丽
    2020-12-01 09:05

    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);
    

提交回复
热议问题