Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run after all javascript ES6 Promises are resolved

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 calls, how can I trigger a function after all the promises are resolved.

Using jQuery Deferreds it would be something like this:

var requests = [...]; //some arbitrary data that is iterated to generate multiple ajax requests
var promises = [];
resuests.forEach(function(endpoint) {
    promises.push($.ajax({url: endpoint}));
});

$.when.apply($, promises).then(function() {
    alert('all promises complete!');
});

How do I rewrite this using ES6 Promise syntax?

like image 922
Dave Avatar asked Oct 29 '14 15:10

Dave


People also ask

Does promise execute After resolve?

resolve() is not a JS control statement that magically would have the effect of return , it's just a function call, and yes, execution continues after it.

How do you wait for promises to complete?

The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result. Here is an example with a promise that resolves in 2 seconds.

What happens when a promise is resolved?

A promise is said to be settled if it is not pending, i.e. if it is either fulfilled or rejected. A promise is resolved if it is settled or if it has been “locked in” to match the state of another promise. Attempting to resolve or reject a resolved promise has no effect.

How do you wait till promise resolves?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.


1 Answers

Since this is tagged bluebird in addition to the two good solutions you have already gotten here is a more "bluebird" way:

var requests = [...];

Promise.map(requests, $.get).then(function(results){
    alert('all promises complete!');
});

This is probably as simple as it gets.

As the others have pointed out, the native es6 way would be to use Promise.all, no Promise.resolve or explicit creation is needed. The cleanest way with native promises would probably be:

var requests = [...];
Promise.all(requests.map($.get)).then(function(results){

});
like image 61
Benjamin Gruenbaum Avatar answered Oct 21 '22 20:10

Benjamin Gruenbaum