File tree Expand file tree Collapse file tree 2 files changed +20
-8
lines changed Expand file tree Collapse file tree 2 files changed +20
-8
lines changed Original file line number Diff line number Diff line change @@ -48,7 +48,7 @@ var asyncReadFile = async function () {
48
48
Generator 函数的执行必须靠执行器,所以才有了` co ` 模块,而` async ` 函数自带执行器。也就是说,` async ` 函数的执行,与普通函数一模一样,只要一行。
49
49
50
50
``` javascript
51
- var result = asyncReadFile ();
51
+ asyncReadFile ();
52
52
```
53
53
54
54
上面的代码调用了` asyncReadFile ` 函数,然后它就会自动执行,输出最后结果。这完全不像 Generator 函数,需要调用` next ` 方法,或者用` co ` 模块,才能真正执行,得到最后结果。
Original file line number Diff line number Diff line change @@ -481,10 +481,7 @@ for (let x of obj) {
481
481
function readLinesSync (file ) {
482
482
return {
483
483
next () {
484
- if (file .isAtEndOfFile ()) {
485
- file .close ();
486
- return { done: true };
487
- }
484
+ return { done: false };
488
485
},
489
486
return () {
490
487
file .close ();
@@ -494,18 +491,33 @@ function readLinesSync(file) {
494
491
}
495
492
```
496
493
497
- 上面代码中,函数` readLinesSync ` 接受一个文件对象作为参数,返回一个遍历器对象,其中除了` next ` 方法,还部署了` return ` 方法。下面,我们让文件的遍历提前返回,这样就会触发执行 ` return ` 方法。
494
+ 上面代码中,函数` readLinesSync ` 接受一个文件对象作为参数,返回一个遍历器对象,其中除了` next ` 方法,还部署了` return ` 方法。下面的三种情况,都会触发执行 ` return ` 方法。
498
495
499
496
``` javascript
497
+ // 情况一
500
498
for (let line of readLinesSync (fileName)) {
501
499
console .log (line);
502
500
break ;
503
501
}
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
+ }
504
514
```
505
515
506
- 注意,` return ` 方法必须返回一个对象,这是Generator规格决定的。
516
+ 上面代码中,情况一输出文件的第一行以后,就会执行` return ` 方法,关闭这个文件;情况二输出所有行以后,执行` return ` 方法,关闭该文件;情况三会在执行` return ` 方法关闭文件之后,再抛出错误。
517
+
518
+ 注意,` return ` 方法必须返回一个对象,这是 Generator 规格决定的。
507
519
508
- ` throw ` 方法主要是配合Generator函数使用 ,一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
520
+ ` throw ` 方法主要是配合 Generator 函数使用 ,一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
509
521
510
522
## for...of循环
511
523
You can’t perform that action at this time.
0 commit comments