Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I execute array of promises in sequential order?

I have an array of promises that need to run in sequential order.

var promises = [promise1, promise2, ..., promiseN]; 

Calling RSVP.all will execute them in parallel:

RSVP.all(promises).then(...);  

But, how can I run them in sequence?

I can manually stack them like this

RSVP.resolve()     .then(promise1)     .then(promise2)     ...     .then(promiseN)     .then(...); 

but the problem is that the number of promises varies and array of promises is built dynamically.

like image 799
jaaksarv Avatar asked Nov 20 '13 15:11

jaaksarv


People also ask

How do you resolve promises sequentially?

The essence of this function is to use reduce starting with an initial value of Promise. resolve([]) , or a promise containing an empty array. This promise will then be passed into the reduce method as promise . This is the key to chaining each promise together sequentially.

How do you run multiple promises together?

Approach 1: In this approach, we will use Promise. all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together.

Does promise all resolve promises in order?

Here, Promise. all() method is the order of the maintained promises. The first promise in the array will get resolved to the first element of the output array, the second promise will be a second element in the output array and so on.


1 Answers

If you already have them in an array then they are already executing. If you have a promise then it's already executing. This is not a concern of promises (I.E they are not like C# Tasks in that regard with .Start() method). .all doesn't execute anything it just returns a promise.

If you have an array of promise returning functions:

var tasks = [fn1, fn2, fn3...];  tasks.reduce(function(cur, next) {     return cur.then(next); }, RSVP.resolve()).then(function() {     //all executed }); 

Or values:

var idsToDelete = [1,2,3];  idsToDelete.reduce(function(cur, next) {     return cur.then(function() {         return http.post("/delete.php?id=" + next);     }); }, RSVP.resolve()).then(function() {     //all executed }); 
like image 54
Esailija Avatar answered Sep 29 '22 19:09

Esailija