Loading topic
for await...of, Symbol.asyncIterator, and async generators all reuse the same ideas, with promises added. This chapter reviews the sync protocol in detail so that the later chapters only have to explain what changes.5 min readasync/await code, and remember the sync iteration protocol from the previous chapter. In that protocol, [Symbol.iterator]() returns an iterator, and the iterator's next() returns { value, done }. Here you 6 min readSymbol.asyncIterator method. That method returns an iterator, and the iterator's next() returns a Promise of a { value, done } result. You can drive that protocol by hand, but the language gives you a loop for i6 min readfor await...of. This chapter covers the producer side. Writing an async iterator object by hand means managing next(), promises, and { value, done } objects yourself. An async generator function writes that object for you. This c6 min readfor await...of consumes an async iterable and how async function* produces one. You should also be comfortable with try/catch around await. The goal is a working model of three things: where errors can start during async iteration, where they show up, and wh5 min readfor await...of an6 min readfor await...of consumes it, and how an early break calls return(). Most of the time an async function* is the simplest way to produce an async sequence. Writing the protocol yourself is still worth learning, for two reas5 min readfor await...of on async iterables, meaning objects with a Symbol.asyncIterator method. The loop also accepts ordinary sync iterables: arrays, strings, Maps, Sets, and sync generators. That fallback is convenient, but it causes several subtle bugs, especially when th6 min readasync/await, Promise.all, and the for await...of loop from earlier chapters. You should also know that for await...of can loop over an array of promises. Here the question is timing. When you write a loop that awaits, how long does th5 min readreadline interfaces, and WHATWG ReadableStream objects (the kind fetch() gives you as response.body) all implement Symbol.asyncIterator. That means for await...of can read them directly. This chapter 6 min readfor await...of loop that re-yields every value. JavaScript also offers a5 min readfor await...of consumes an async iterable, how async function* produces one, and how break or return inside a loop calls the iterator's return() method. You should also be comfortable with yield* delegation and with try/finally inside generator6 min readArray.fromAsync does this in one call. It is the async counterpart of Array.from.5 min read