mirror of
https://github.com/NohamR/knowledge-kit.git
synced 2026-05-25 04:17:17 +00:00
docs: 批量博文
This commit is contained in:
54
Chapter2 - Web FrontEnd/2.4.md
Normal file
54
Chapter2 - Web FrontEnd/2.4.md
Normal file
@@ -0,0 +1,54 @@
|
||||
# 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>
|
||||
```
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user