-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
49 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters