mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-29 13:52:22 +00:00
docs(async): add 异步 Generator 函数的例子
This commit is contained in:
parent
f301b5d989
commit
618a150053
@ -795,7 +795,33 @@ genObj.next().then(x => console.log(x));
|
||||
|
||||
上面代码中,`gen`是一个异步 Generator 函数,执行后返回一个异步 Iterator 对象。对该对象调用`next`方法,返回一个 Promise 对象。
|
||||
|
||||
下面是另一个例子。
|
||||
异步遍历器的设计目的之一,就是 Generator 函数处理同步操作和异步操作时,能够使用同一套接口。
|
||||
|
||||
```javascript
|
||||
// 同步 Generator 函数
|
||||
function* map(iterable, func) {
|
||||
const iter = iterable[Symbol.iterator]();
|
||||
while (true) {
|
||||
const {value, done} = iter.next();
|
||||
if (done) break;
|
||||
yield func(value);
|
||||
}
|
||||
}
|
||||
|
||||
// 异步 Generator 函数
|
||||
async function* map(iterable, func) {
|
||||
const iter = iterable[Symbol.asyncIterator]();
|
||||
while (true) {
|
||||
const {value, done} = await iter.next();
|
||||
if (done) break;
|
||||
yield func(value);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
上面代码中,可以看到有了异步遍历器以后,同步 Generator 函数和异步 Generator 函数的写法基本上是一致的。
|
||||
|
||||
下面是另一个异步 Generator 函数的例子。
|
||||
|
||||
```javascript
|
||||
async function* readLines(path) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user