Page 136 - JavaScript
P. 136

Chapter 9: Async Iterators




        Introduction



        An async function is one that returns a promise. await yields to the caller until the promise resolves
        and then continues with the result.

        An iterator allows the collection to be looped through with a for-of loop.


        An async iterator is a collection where each iteration is a promise which can be awaited using a
        for-await-of loop.


        Async iterators are a stage 3 proposal. They are in Chrome Canary 60 with --harmony-async-
        iteration


        Syntax


            •  async function* asyncGenerator() {}
            •  yield await asyncOperationWhichReturnsAPromise();
            •  for await (let result of asyncGenerator()) { /* result is the resolved value from the promise */ }



        Remarks


        An async iterator is a declarative pull stream as opposed to an Observable's declarative push
        stream.


        Useful Links


            •  Async Iteration spec proposal
            •  Introduction to their use
            •  Event subscription proof of concept


        Examples



        Basics


        A JavaScript Iterator is an object with a .next() method, which returns an IteratorItem, which is
        an object with value : <any> and done : <boolean>.

        A JavaScript AsyncIterator is an object with a .next() method, which returns a
        Promise<IteratorItem>, a promise for the next value.


        To create an AsyncIterator, we can use the async generator syntax:


         /**



        https://riptutorial.com/                                                                               93
   131   132   133   134   135   136   137   138   139   140   141