7

Here is a timer function

const timer = (time) => {
  return new Promise((resolve, reject) => {
    console.log(`${time} timer start`);
    setTimeout(() => {
      console.log(`${time} timer end`);
      resolve();
    }, time);
  });
};

I'm going to call this timer function with 'for await of` and 'for of'.

First, 'for await of'

async function runForAwaitOf() {
  const times = [300, 100, 700, 500];

  for await (let time of times) {
      await timer(time);
  }

  console.log('All the timers end');
}
runForAwaitOf()

Second, 'for of'

async function runForOf() {
  const times = [300, 100, 700, 500];

  for (let time of times) {
      await timer(time);
  }

  console.log('All the timers end');
}
runForOf()

When I ran above codes, I don't see any differences between them.

If they results the sames, why does ECMA make for await of?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
jspking
  • 73
  • 6
  • 1
    `for...await of` is about handling async iterators, not just handling iterables of promises. – VLAZ Oct 08 '22 at 14:40
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of#description MDN explains the differences quite well, just look for the list of differences in the description – Challe Oct 08 '22 at 14:42
  • 1
    Related: [for await of VS Promise.all](https://stackoverflow.com/q/59694309) | [Using for await...of with synchronous iterables](https://stackoverflow.com/q/60706179) – VLAZ Oct 08 '22 at 14:47
  • @VLAZ I'd even close as a duplicate, would you disagree? – Bergi Oct 08 '22 at 16:18
  • @Bergi I won't disagree. – VLAZ Oct 08 '22 at 17:07

1 Answers1

5

for await can be used for consuming async iterables. It can also consume standard iterables (like the one in your question) - but with standard iterables, it won't appear any different from using for..of.

For an example of an async iterable for which for await could be useful:

const delay = ms => new Promise(res => setTimeout(res, ms));
async function* multiTimer() {
  await delay(1000);
  yield 1;
  await delay(2000);
  yield 2;
  await delay(3000);
  yield 3;
  await delay(1000);
  yield 4;
};
(async () => {
  for await (const time of multiTimer()) {
      console.log('got', time);
  }
  console.log('All the timers end');
})();

If you have a standard iterable, you should use for..of, and if you have an async iterable, you should use for await..of. They're designed for different situations.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320