How can I wait for set of asynchronous callback functions?

前端 未结 6 1871
感动是毒
感动是毒 2020-11-22 09:07

I have code that looks something like this in javascript:

forloop {
    //async call, returns an array to its callback
}

After ALL of those

6条回答
  •  庸人自扰
    2020-11-22 09:45

    Checking in from 2015: We now have native promises in most recent browser (Edge 12, Firefox 40, Chrome 43, Safari 8, Opera 32 and Android browser 4.4.4 and iOS Safari 8.4, but not Internet Explorer, Opera Mini and older versions of Android).

    If we want to perform 10 async actions and get notified when they've all finished, we can use the native Promise.all, without any external libraries:

    function asyncAction(i) {
        return new Promise(function(resolve, reject) {
            var result = calculateResult();
            if (result.hasError()) {
                return reject(result.error);
            }
            return resolve(result);
        });
    }
    
    var promises = [];
    for (var i=0; i < 10; i++) {
        promises.push(asyncAction(i));
    }
    
    Promise.all(promises).then(function AcceptHandler(results) {
        handleResults(results),
    }, function ErrorHandler(error) {
        handleError(error);
    });
    

提交回复
热议问题