amir hodaee
amir hodaee

Reputation: 47

handling promises in parallel

i have a socket connection from my client service and receive an array of data. based on each element in array i will create query and send to database. how can i resolve this promises asynchronously?

Promise.all([p1, p2, p3, ...)

promise all is not useful for me because i need an event emitted after any of them is resolved.

each time any of this promises is resolved, i should do some job.

so i wondering if there is any way to receive an event per each promises?

Upvotes: 1

Views: 134

Answers (3)

Fan Cheung
Fan Cheung

Reputation: 11370

The rxjs solution is to use merge

merge(from(p1),from(p2),from(p3))
.subscribe(()=>{.. will execute when any one of promise complete})

Upvotes: 1

jfriend00
jfriend00

Reputation: 707856

If you want:

  1. Run then in parallel.
  2. Do something when each promise finishes
  3. Know when they are all done

You can do this:

Promise.all([
    p1.then(result => { /* do something when p1 is done; return result; */}),
    p2.then(result => { /* do something when p2 is done; return result; */}),
    p3.then(result => { /* do something when p3 is done; return result; */}),
]).then(allResults => {
    console.log("all promises done");
}).catch(err => {
    console.log(err);
});

If you wanted to know when all of them were finished, even if some had an error:

Promise.allSettled([
    p1.then(result => { /* do something when p1 is done; return result; */}),
    p2.then(result => { /* do something when p2 is done; return result; */}),
    p3.then(result => { /* do something when p3 is done; return result; */}),
]).then(settledResults => {
    console.log("all promises done");
});

Now, usually, you wouldn't have p1, p2 and p3 in separate variables like this. Usually, you would just make the function calls directly like this:

Promise.all([
    fn1(arg1).then(result => { /* do something when fn1 is done; return result; */}),
    fn2(arg2).then(result => { /* do something when fn2 is done; return result; */}),
    fn3(arg3).then(result => { /* do something when fn3 is done; return result; */}),
]).then(allResults => {
    console.log("all promises done");
}).catch(err => {
    console.log(err);
});

Upvotes: 0

Oursin
Oursin

Reputation: 141

You could simply loop over the promise array and attach a .then handler to all of them, like this

const promises = [p1, p2, p3, ...]
for (const promise of promises) {
    promise.then(() => console.log('done'));
}

Upvotes: 1

Related Questions