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:
parent
1a21fb8ea1
commit
2eeb5a1edc
@ -48,7 +48,7 @@ var asyncReadFile = async function () {
|
||||
Generator 函数的执行必须靠执行器,所以才有了`co`模块,而`async`函数自带执行器。也就是说,`async`函数的执行,与普通函数一模一样,只要一行。
|
||||
|
||||
```javascript
|
||||
var result = asyncReadFile();
|
||||
asyncReadFile();
|
||||
```
|
||||
|
||||
上面的代码调用了`asyncReadFile`函数,然后它就会自动执行,输出最后结果。这完全不像 Generator 函数,需要调用`next`方法,或者用`co`模块,才能真正执行,得到最后结果。
|
||||
|
@ -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,15 +491,30 @@ 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`方法,关闭这个文件;情况二输出所有行以后,执行`return`方法,关闭该文件;情况三会在执行`return`方法关闭文件之后,再抛出错误。
|
||||
|
||||
注意,`return`方法必须返回一个对象,这是 Generator 规格决定的。
|
||||
|
||||
`throw`方法主要是配合 Generator 函数使用,一般的遍历器对象用不到这个方法。请参阅《Generator函数》一章。
|
||||
|
Loading…
x
Reference in New Issue
Block a user