r/JavaScriptTips • • Jan 16 '23

Promises can be consumed sequentially by using await in a loop

Post image
18 Upvotes

7 comments sorted by

1

u/Low_Mammoth_9371 Jan 16 '23

Code to copy:

const promises = [
  
  () => new Promise(res => setTimeout(() => res("1"), 2000)),
  
  () => new Promise(res => setTimeout(() => res("2"), 2000)),
  
  () => new Promise(res => setTimeout(() => res("3"), 2000)),

];


async function handler() {

  for (let promise of promises) {

    const value = await promise();

    console.log(value);
    // 2 sec: "1"
    // 4 sec: "2"
    // 6 sec: "3"

  }

}

handler();

1

u/SuperLeo_0 Jan 16 '23

how about Promise.all()?

1

u/Low_Mammoth_9371 Jan 16 '23

That won't run promises sequentially (one after another). Instead it will start all promises at the same time and return all values if all are successful and throw an error otherwise.

1

u/SuperLeo_0 Jan 16 '23

Yeah i forgot.