Use an Array of Promises with a For Await Of Loop

John Lindquist
InstructorJohn Lindquist
Share this video with your friends

Social Share Links

Send Tweet
Published 5 years ago
Updated 4 years ago

The "for await of" loop syntax enables you to loop through an Array of Promises and await each of the responses asynchronously. This lesson walks you through creating the array and awaiting each of the results.

John Lindquist: [00:00] When you create an array of Promises -- we'll call this promises, and create two promises, Promise.resolve(1) and Promise.resolve(2) inside of an async function, which we'll name start() -- you can use a for of loop just like you would with any other iterable. The promises is an iterable, so say promise of promises. Then we can console.log(promise).

[00:24] We'll go ahead and start our program, save here. You can see we get two Promises logged out in the console. Because we marked our function as async, you can add the additional await keyword making this a for await of loop, which will treat this as an iterator that contains promises. When I hit save here, you can see that it awaits each value coming through.

[00:46] If I create a third promise, we'll say new Promise(), and we'll create a function which takes our resolve, and we'll setTimeout to resolve(3) after three seconds. I'll hit save here. You can see 1, 2, and then after three seconds, 3.

egghead
egghead
~ 44 seconds ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today