File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -48,7 +48,7 @@ var asyncReadFile = async function () {
4848Generator 函数的执行必须靠执行器,所以才有了` co ` 模块,而` async ` 函数自带执行器。也就是说,` async ` 函数的执行,与普通函数一模一样,只要一行。
4949
5050``` javascript
51- var result = asyncReadFile ();
51+ asyncReadFile ();
5252```
5353
5454上面的代码调用了` asyncReadFile ` 函数,然后它就会自动执行,输出最后结果。这完全不像 Generator 函数,需要调用` next ` 方法,或者用` co ` 模块,才能真正执行,得到最后结果。
Original file line number Diff line number Diff line change @@ -481,10 +481,7 @@ for (let x of obj) {
481481function readLinesSync (file ) {
482482 return {
483483 next () {
484- if (file .isAtEndOfFile ()) {
485- file .close ();
486- return { done: true };
487- }
484+ return { done: false };
488485 },
489486 return () {
490487 file .close ();
@@ -494,18 +491,33 @@ function readLinesSync(file) {
494491}
495492```
496493
497- 上面代码中,函数` readLinesSync ` 接受一个文件对象作为参数,返回一个遍历器对象,其中除了` next ` 方法,还部署了` return ` 方法。下面,我们让文件的遍历提前返回,这样就会触发执行 ` return ` 方法。
494+ 上面代码中,函数` readLinesSync ` 接受一个文件对象作为参数,返回一个遍历器对象,其中除了` next ` 方法,还部署了` return ` 方法。下面的三种情况,都会触发执行 ` return ` 方法。
498495
499496``` javascript
497+ // 情况一
500498for (let line of readLinesSync (fileName)) {
501499 console .log (line);
502500 break ;
503501}
502+
503+ // 情况二
504+ for (let line of readLinesSync (fileName)) {
505+ console .log (line);
506+ continue ;
507+ }
508+
509+ // 情况三
510+ for (let line of readLinesSync (fileName)) {
511+ console .log (line);
512+ throw new Error ();
513+ }
504514```
505515
506- 注意,` return ` 方法必须返回一个对象,这是Generator规格决定的。
516+ 上面代码中,情况一输出文件的第一行以后,就会执行` return ` 方法,关闭这个文件;情况二输出所有行以后,执行` return ` 方法,关闭该文件;情况三会在执行` return ` 方法关闭文件之后,再抛出错误。
517+
518+ 注意,` return ` 方法必须返回一个对象,这是 Generator 规格决定的。
507519
508- ` throw ` 方法主要是配合Generator函数使用 ,一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
520+ ` throw ` 方法主要是配合 Generator 函数使用 ,一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
509521
510522## for...of循环
511523
You can’t perform that action at this time.
0 commit comments