Skip to content Skip to sidebar Skip to footer

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 of

Solution 1:

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.


Post a Comment for "How Do I Resolve Multiple Promises As They Resolve?"