Jayde
Jayde

Reputation: 57

How do I resolve multiple promises as they resolve?

Lets say, for example, I have three promises. One that will take 1000ms to resolve, another that takes 2000ms to resolve, and a third that takes 3000ms to resolve.

How do I kick off all promises at the same time, and handle each resolved promise, as they happen.

For example.

let fastPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve(""), 1000);
});

let mediumPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve(""), 2000);
});

let slowPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve(""), 4000);
});

In this case I would want to start all three promises at the same time, and handle them as they resolve, in order. i.e. handle fastPromise, then mediumPromise, then slowPromise.

Upvotes: 0

Views: 635

Answers (1)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

If for some reason, you are looking for a way to have some kind of a common handler for all the Promises, you can do it that way:

const fastPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("fast"), 1000);
});

const mediumPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("medium"), 2000);
});

const slowPromise = new Promise((resolve, reject) => {
    setTimeout(() => resolve("slow"), 4000);
});

function commonHandler(result) {
  console.log(result);
}

[fastPromise, mediumPromise, slowPromise].forEach((p) => p.then(commonHandler));

(don't forget to add .catch() the same way).

However, if you want to just fire X Promises and handle them using X handlers as they resolve, then... it's default Promise behavior and there's nothing to do other than adding .then() to each of the Promises really.

Upvotes: 2

Related Questions