javascriptasync-awaitfor-await

desugaring for await .. of


Have been trying to figure out what exactly for await .. of does. However, even reading the specs I haven't been able to find exactly what it does.

Here is my guess:

const it = iterable[Synbol.asyncIterator]();
while (true) {
  const { done, value } = await it.next();
  if (done) return;
  // User code...
}

However, if the iterator implements return and throw I'm not sure where/how they come into play?

One guess is:

const it = iterable[Synbol.asyncIterator]();
try {
  while (true) {
    const { done, value } = await it.next();
    if (done) return;
    try { 
      // User code...
    } catch (err) {
      const { done } = await it.throw(err);
      if (done) return;
    }
  }
} finally {
  it.return();
}

Solution

  • The throw method of the iterator is not used at all in the iteration protocol.

    The return method of the iterator is called if the user code evaluates to an abrupt completion that prematurely ends the iteration (i.e. before (await it.next()).done is true):

    The steps of the AsyncIteratorClose procedure are really hard to accurately represent as JS code, so I'll avoid presenting an attempt at desugaring.

    The for await … of steps are exactly those of the for … of loop, except for accessing the iterator by Symbol.asyncIterator instead of Symbol.iterator, and awaiting the return values of .next() and .return() invocations.