Skip to content

Better example for for await..of #60

@illiteratewriter

Description

@illiteratewriter

The example

async function fetch_fruits() {
  const fruits = ["apple", "banana", "orange", "grape"];

  for await (const fruit of fruits) {
    console.log(fruit);

    // a dummy async operation simulation
    await new Promise((resolve) => setTimeout(resolve, 1000));
  }
}

fetch_fruits();

which is provided will work even if we remove the await in the for await..of loop and replace it with a for..of loop.

Wouldn't a better example be something like

async function fetch_fruits() {
  const fruits = [
    new Promise((resolve) => setTimeout(() => resolve("apple"), 1000)),
    new Promise((resolve) => setTimeout(() => resolve("banana"), 500)),
    new Promise((resolve) => setTimeout(() => resolve("orange"), 5000)),
    new Promise((resolve) => setTimeout(() => resolve("grape"), 1000)),
  ];

  for await (const fruit of fruits) {
    console.log(fruit);
  }
}

fetch_fruits();

In this example if we remove await in the for await..of loop, then the response will be an array of promises.

This is from chapter 03, working with files under the heading for await..of

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions