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
+19 -7
View File
@@ -481,10 +481,7 @@ for (let x of obj) {
function readLinesSync(file) {
return {
next() {
if (file.isAtEndOfFile()) {
file.close();
return { done: true };
}
return { done: false };
},
return() {
file.close();
@@ -494,18 +491,33 @@ function readLinesSync(file) {
}
```
上面代码中,函数`readLinesSync`接受一个文件对象作为参数,返回一个遍历器对象,其中除了`next`方法,还部署了`return`方法。下面,我们让文件的遍历提前返回,这样就会触发执行`return`方法。
上面代码中,函数`readLinesSync`接受一个文件对象作为参数,返回一个遍历器对象,其中除了`next`方法,还部署了`return`方法。下面的三种情况,都会触发执行`return`方法。
```javascript
// 情况一
for (let line of readLinesSync(fileName)) {
console.log(line);
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循环