1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 18:32:22 +00:00

docs(iterator): edit iterator.return()

This commit is contained in:
ruanyf 2017-08-08 08:13:24 +08:00
parent 1a21fb8ea1
commit 2eeb5a1edc
2 changed files with 20 additions and 8 deletions

View File

@ -48,7 +48,7 @@ var asyncReadFile = async function () {
Generator 函数的执行必须靠执行器,所以才有了`co`模块,而`async`函数自带执行器。也就是说,`async`函数的执行,与普通函数一模一样,只要一行。 Generator 函数的执行必须靠执行器,所以才有了`co`模块,而`async`函数自带执行器。也就是说,`async`函数的执行,与普通函数一模一样,只要一行。
```javascript ```javascript
var result = asyncReadFile(); asyncReadFile();
``` ```
上面的代码调用了`asyncReadFile`函数,然后它就会自动执行,输出最后结果。这完全不像 Generator 函数,需要调用`next`方法,或者用`co`模块,才能真正执行,得到最后结果。 上面的代码调用了`asyncReadFile`函数,然后它就会自动执行,输出最后结果。这完全不像 Generator 函数,需要调用`next`方法,或者用`co`模块,才能真正执行,得到最后结果。

View File

@ -481,10 +481,7 @@ for (let x of obj) {
function readLinesSync(file) { function readLinesSync(file) {
return { return {
next() { next() {
if (file.isAtEndOfFile()) { return { done: false };
file.close();
return { done: true };
}
}, },
return() { return() {
file.close(); file.close();
@ -494,18 +491,33 @@ function readLinesSync(file) {
} }
``` ```
上面代码中,函数`readLinesSync`接受一个文件对象作为参数,返回一个遍历器对象,其中除了`next`方法,还部署了`return`方法。下面,我们让文件的遍历提前返回,这样就会触发执行`return`方法。 上面代码中,函数`readLinesSync`接受一个文件对象作为参数,返回一个遍历器对象,其中除了`next`方法,还部署了`return`方法。下面的三种情况,都会触发执行`return`方法。
```javascript ```javascript
// 情况一
for (let line of readLinesSync(fileName)) { for (let line of readLinesSync(fileName)) {
console.log(line); console.log(line);
break; break;
} }
// 情况二
for (let line of readLinesSync(fileName)) {
console.log(line);
continue;
}
// 情况三
for (let line of readLinesSync(fileName)) {
console.log(line);
throw new Error();
}
``` ```
注意,`return`方法必须返回一个对象这是Generator规格决定的。 上面代码中,情况一输出文件的第一行以后,就会执行`return`方法,关闭这个文件;情况二输出所有行以后,执行`return`方法,关闭该文件;情况三会在执行`return`方法关闭文件之后,再抛出错误
`throw`方法主要是配合Generator函数使用一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。 注意,`return`方法必须返回一个对象,这是 Generator 规格决定的。
`throw`方法主要是配合 Generator 函数使用一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
## for...of循环 ## for...of循环