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();
  • 相关阅读:
    常用的算法
    2017前端面试题
    深入了解php opcode缓存原理
    0=='aa'的结果是true
    关于PHP浮点数之 intval((0.1+0.7)*10) 为什么是7
    linux grep命令
    linux awk命令详解
    PHP socket模拟POST请求
    shell编程之sed
    Shell脚本常用判断
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8343516.html
Copyright © 2011-2022 走看看