Skip to content

Commit

Permalink
生成器 generator
Browse files Browse the repository at this point in the history
  • Loading branch information
dptms committed Oct 26, 2017
1 parent d156eb8 commit 7ac2d6f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
46 changes: 46 additions & 0 deletions 19.generator.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# 生成器
> `javascript` 中的函数,都是从上到下依次执行,直到结束,生成器的函数,可以在执行中开始、暂停,并可以在以后的调用中传入另外的参数。
```js
// 关键字 `*`
function* listColors() {
console.log('test');
// 关键字 `yield` 相当于 `return` ,但是 `ruturn` 本次执行的返回值
yield 'red';
yield 'blue';
yield 'green';
}

// 返回一个生成器对象 在这里不会打印 `console.log('test')` 只有在执行 `next` 的时候才会有打印
const colors = listColors();
// 在每次调用 `next()` 方法的过程中有点像迭代器,依次返回 `yield` 指定的返回值
colors.next(); // {value: "red", done: false}
colors.next(); // {value: "blue", done: false}
colors.next(); // {value: "green", done: false}
colors.next(); // {value: undefined, done: true}
```

### 应用
```js
// 使用 `Generator` 生成器 控制 `ajax` 工作流
function ajax(url) {
axios.get(url).then(res => userGen.next(res.data));
}

function* steps() {
console.log('fetching users');
const users = yield ajax('https://api.github.com/users');
console.log(users);

console.log('fetching firstUser');
const firstUser = yield ajax(`https://api.github.com/users/${users[0].login}`);
console.log(firstUser);

console.log('fetching followers');
const followers = yield ajax(firstUser.followers_url);
console.log(followers);
}

const userGen = steps();
userGen.next();
```
4 changes: 3 additions & 1 deletion README.MD
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,6 @@
* [Promise](https://github.com/dptms/es6/blob/master/14.promise-intro.md)
* [Symbol](https://github.com/dptms/es6/blob/master/15.symbol.md)
* [模块](https://github.com/dptms/es6/blob/master/16.modules.md)
* [](https://github.com/dptms/es6/blob/master/17.classes.md)
* [](https://github.com/dptms/es6/blob/master/17.classes.md)
* [遍历器 迭代器](https://github.com/dptms/es6/blob/master/18.iterator.md)
* [生成器](https://github.com/dptms/es6/blob/master/18.generator.md)

0 comments on commit 7ac2d6f

Please sign in to comment.