Skip to content

Commit 618a150

Browse files
committed
docs(async): add 异步 Generator 函数的例子
1 parent f301b5d commit 618a150

File tree

1 file changed

+27
-1
lines changed

1 file changed

+27
-1
lines changed

docs/async.md

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -795,7 +795,33 @@ genObj.next().then(x => console.log(x));
795795

796796
上面代码中,`gen`是一个异步 Generator 函数,执行后返回一个异步 Iterator 对象。对该对象调用`next`方法,返回一个 Promise 对象。
797797

798-
下面是另一个例子。
798+
异步遍历器的设计目的之一,就是 Generator 函数处理同步操作和异步操作时,能够使用同一套接口。
799+
800+
```javascript
801+
// 同步 Generator 函数
802+
function* map(iterable, func) {
803+
const iter = iterable[Symbol.iterator]();
804+
while (true) {
805+
const {value, done} = iter.next();
806+
if (done) break;
807+
yield func(value);
808+
}
809+
}
810+
811+
// 异步 Generator 函数
812+
async function* map(iterable, func) {
813+
const iter = iterable[Symbol.asyncIterator]();
814+
while (true) {
815+
const {value, done} = await iter.next();
816+
if (done) break;
817+
yield func(value);
818+
}
819+
}
820+
```
821+
822+
上面代码中,可以看到有了异步遍历器以后,同步 Generator 函数和异步 Generator 函数的写法基本上是一致的。
823+
824+
下面是另一个异步 Generator 函数的例子。
799825

800826
```javascript
801827
async function* readLines(path) {

0 commit comments

Comments
 (0)