user6124024
user6124024

Reputation:

Dynamic array promise sequence

Im getting dynamic (the number of promises can be change each per runtime) array of promises, Now I want that after every resolve or reject to handle the returned promise before promises array will be finished .

I try with promise all but it's continue after all the promises has done.

if the array (of promises) wasn't be dynamic so I can simply use something like this but I dont know how much promises I have in the array and I want after every promise fulfilled or ... to proceed with the answer of it and not wait until all the promises will done

firstMethod()
   .then(secondMethod)
   .then(thirdMethod);

We are using Q ...

Is it possible ?

Update (example )

Lets say I've the promise array

[promise1,promise2,promise3, promiseN]

Now I want that when promise1 finish to process to handle it with then and not wait that all promises will be finished .

The biggest issue here is the array can have N promises and I dont know in RT how much promises I will get until I got this array therefore I cannot use simply then

Update 2 (to clarify a bit more :-) ) The tricky part...

If I Know the size of the array beforehand I can use simply then , 5 entry in the array 5 chain with then but here the tricky part is that I dont know beforehand how much promises I will have in the array of the promises ....

Upvotes: 6

Views: 4333

Answers (3)

amir hosein ahmadi
amir hosein ahmadi

Reputation: 262

you can use Promise.race()

The Promise.race(iterable) method returns a promise that resolves or rejects as soon as one of the promises in the iterable resolves or rejects, with the value or reason from that promise.

var p1 = new Promise(function(resolve, reject) { 
    setTimeout(resolve, 500, 'one'); 
});
var p2 = new Promise(function(resolve, reject) { 
    setTimeout(resolve, 100, 'two'); 
});

Promise.race([p1, p2]).then(function(value) {
  console.log(value); // "two"
  // Both resolve, but p2 is faster
});

Upvotes: 2

Estus Flask
Estus Flask

Reputation: 222474

If the goal is to chain each promise with same then but to not wait for all promises to complete, this is just a loop:

for (const promise of promiseArray) {
  promise.then(...)
}

If promise results should be joined together in the end, the array can be additionally processed by all:

Promise.all(promiseArray.map(promise => promise.then(...)))
.then(...)

Notice that behaviour for all applies here. If there is uncaught rejection in promise array, only the first rejection will be caught.

This is true for most promise implementations. There may be Q methods that allow do do this easier.

Upvotes: 4

Tomasz Kasperek
Tomasz Kasperek

Reputation: 1187

If you don't need to chain promises. You could just do:

var tasks = [[promise1, handler1], [promise2, handler2], [promise3, handler3]];

tasks.forEach(function (task) {
  var promise = task[0];
  var handler = task[1];
  promise.then(handler)
});

Upvotes: 1

Related Questions