How to run after all javascript ES6 Promises are resolved

I'm in the process of replacing old code that used jQuery Deferred objects, and I'm rewriting with Bluebird / ES6 Promises.

If I have several asynchronous calls, how can I call the 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 Promise ES6 syntax?

+5
source share
2 answers

Since this is tagged in addition to the two good solutions you already got here, it is a more bluebird:

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

This is probably as simple as it gets.

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

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

Using Promise.all . Note that it takes an iterative array such as Array as an argument, unlike $.when , so $.when is not needed.

You will also want to convert jQuery Deferred to a native ES6 promise using Promise.resolve(thejQueryDeferred) . EDIT: this happens implicitly on a call to Promise.all , so this is really optional.

All 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!'); }); 
+5
source

Source: https://habr.com/ru/post/1205791/


All Articles