[TypeScript] Asynchronous Iteration using for-await-of

The for-await-of syntax is similar to the for-of iteration. The key difference is that it automatically awaits any promises generated by the iterator. This lesson covers how to consume async data sources easily with for-await-of.

for-await-of essentially allows you to use async/await in a generator function.

 

import { magic } from './server';

(Symbol as any).asyncIterator =
  (Symbol as any).asyncIterator
  || Symbol.for("Symbol.asyncIterator");

async function* numbers() {
  let index = 1;
  while (true) {
    yield index;
    index = await magic(index);
    if (index > 10) {
      break;
    }
  }
}

async function main() {
  for await (const num of numbers()) {
    console.log(num);
  }
}
main();

 

Server:

const magic = (i: number) => new Promise<number>(res => setTimeout(res(i + 1), 100));

 

Example 2:

// Asynchronous generators

async function asyncGenerators () {
    async function* createAsyncIterable(syncIterable) {
        for (const elem of syncIterable) {
            yield elem;
        }
    }
    
    const asyncGenObj = createAsyncIterable(['a', 'b']);
    const [{value:v1}, {value:v2}] = await Promise.all([
        asyncGenObj.next(), asyncGenObj.next()
    ]);
    console.log("v1", v1, "v2", v2); // a, b
}
asyncGenerators();

 

posted @ 2018-01-24 20:55  Zhentiw  阅读(372)  评论(0编辑  收藏  举报