博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[TypeScript] Asynchronous Iteration using for-await-of
阅读量:4698 次
发布时间:2019-06-09

本文共 1282 字,大约阅读时间需要 4 分钟。

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
(res => setTimeout(res(i + 1), 100));

 

Example 2:

// Asynchronous generatorsasync 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();

 

转载于:https://www.cnblogs.com/Answer1215/p/8343516.html

你可能感兴趣的文章
C++学习:任意合法状态下汉诺塔的移动(原创)
查看>>
leetcode133 - Clone Graph - medium
查看>>
一点小基础
查看>>
PHP 自动加载类 __autoload() 方法
查看>>
JDK中的Timer和TimerTask详解(zhuan)
查看>>
【python练习】ATM&购物商城程序
查看>>
nginx 日志问题(\x22)
查看>>
装饰器、迭代器、生成器
查看>>
类对象作为类成员
查看>>
面向对象和面向过程的区别及优劣对比详解
查看>>
const与指针
查看>>
thsi指针的一些用法及作用
查看>>
c++友元
查看>>
c++运算符重载
查看>>
一元运算符重载
查看>>
Windows 远程栈溢出挖掘
查看>>
(网页)the server responded with a status of 403 (Forbidden)
查看>>
葡萄城报表介绍:Java 报表
查看>>
android 通知消息一
查看>>
UNET学习笔记2 - 高级API(HLAPI)
查看>>