Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Better example for for await..of #60

Open
illiteratewriter opened this issue Sep 19, 2024 · 0 comments
Open

Better example for for await..of #60

illiteratewriter opened this issue Sep 19, 2024 · 0 comments

Comments

@illiteratewriter
Copy link
Contributor

illiteratewriter commented Sep 19, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant