zoukankan      html  css  js  c++  java
  • [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();
  • 相关阅读:
    很难理解的三个设计模式
    设计模式思考(转)
    AOP
    CAP理论(摘)
    DDBS
    NoSql
    Enterprise Library 企业库
    padright padleft
    Process ProcessThread Thread
    053374
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8343516.html
Copyright © 2011-2022 走看看