File tree Expand file tree Collapse file tree 1 file changed +27
-1
lines changed Expand file tree Collapse file tree 1 file changed +27
-1
lines changed Original file line number Diff line number Diff 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
801827async function * readLines (path ) {
You can’t perform that action at this time.
0 commit comments