How to run after all javascript ES6 Promises are resolved

后端 未结 2 1874
我寻月下人不归
我寻月下人不归 2020-12-11 06:12

I\'m in the process of replacing some old code that used jQuery Deferred objects and I am rewriting using Bluebird/ES6 Promises.

If I have multiple asynchronous call

2条回答
  •  情话喂你
    2020-12-11 06:42

    Using Promise.all. Note that it takes an iterable such as an Array as its argument, unlike $.when, so doesn't need the .apply.

    You'll also want to convert the jQuery Deferred to a native ES6 promise using Promise.resolve(thejQueryDeferred). EDIT: This gets done implicitly by the call to Promise.all, so is really optional.

    Whole code:

    var requests = [...]; //some arbitrary data that is iterated to generate multiple ajax requests
    var promises = [];
    requests.forEach(function(endpoint) {
        var nativePromise = Promise.resolve($.ajax({url: endpoint})); // if you want to make it clear that you're converting from jQuery Deferred to ES6 promise!
        promises.push(nativePromise);
    });
    
    Promise.all(promises).then(function() {
        alert('all promises complete!');
    });
    

提交回复
热议问题