r/JavaScriptTips • • Feb 06 '23

Options for handling multiple promises

Post image
25 Upvotes

6 comments sorted by

1

u/Low_Mammoth_9371 Feb 06 '23

Code to copy below, YT tutorial here: https://youtu.be/LE_L9OAh6Hk

const makeCoffee = new Promise((resolve, reject) => {
    setTimeout(() => resolve("β˜•"), 200) });

const makeBreakfast = new Promise((resolve, reject) => {
    setTimeout(() => resolve("🍳"), 800) });

const goToWork = new Promise((resolve, reject) => {
    setTimeout(() => resolve("πŸƒβ€β™‚οΈ"), 2000) });

const promises = [makeCoffee, makeBreakfast, goToWork];


// Joint handling options (choose one):

Promise.all(promises).then(res => console.log(res));
// Logs result of all promises, if and when all successful

Promise.allSettled(promises).then(res => console.log(res));
// Logs results of all, even if one fails

Promise.any(promises).then(res => console.log(res));
// Logs result of fastest successful promise

Promise.race(promises).then(res => console.log(res));
// Logs result of fastest promise, even if it fails

promises.forEach(async promise => console.log(await promise));
// Logs results in order, as soon as each completes

1

u/Kukissiku Feb 07 '23

Graet info!

1

u/letsfed Feb 06 '23

Nice one but I think it’s better to not use async in the forEach due its nature

1

u/O_crl Feb 06 '23

I know you shouldn't mix async await premises with Promises, but I would like to know what actually can happen.

1

u/letsfed Feb 06 '23

Simply you are not waiting the promises


const promises = [Promise.resolve(1), Promise.resolve(2), Promise.resolve(3)];

promises.forEach(async promise => console.log(await promise));

console.log('After run');

It will result in

  • After run

  • 1

  • 2

  • 3

Also, error handling is not present, but I suspect it's just for brevity.

1

u/Hakim_Bey Feb 06 '23

yeah you'd be better off using for...of in that case