Files
knowledge-kit/Chapter2 - Web FrontEnd/2.4.md
2020-02-25 17:46:51 +08:00

55 lines
1.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# generator函数
generator生成器是ES6标准引入的新的数据类型一个generator看上起像一个函数但是可以返回多次.
```
<script>
'use strict';
function* foo(max) {
var n = 0;
while (n < max) {
yield n;
n++;
}
return n;
}
var f = foo(3);
//方式1
console.log(f.next());
console.log(f.next());
console.log(f.next());
console.log(f.next());
//方式2
for (var f of foo(3)) {
console.log(f);
}
</script>
```
* next\(\)方法会执行一个generator的代码然后每次遇到yield x就返回一个对象{value:x,done:true/false},然后暂停。返回的value就是yield的返回值done表示这个generator是否已经执行结束了如果为done为true则value就是return的返回值。
* 当执行到done为true时这个generator对象就已经全部执行完毕就不要再继续调用next\(\)
* 第2个方法就是直接调用for...of循环迭代generator对象这种方式不需要我们自己判断done
#### 优点
generator可以把异步代码变成“同步”代码
```
<script>
try {
r1 = yield ajax("http://test1.com/get", data1);
r2 = yield ajax("http://test1.com/get", data1);
r3 = yield ajax("http://test1.com/get", data1);
success(r3);
} catch (e) {
//TODO handle the exception
handle(e);
}
</script>
```