From 7ac2d6fb40a176d9f54977bdb82ceb5e84290e3d Mon Sep 17 00:00:00 2001 From: dp~ <457509824@qq.com> Date: Thu, 26 Oct 2017 17:40:33 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=9F=E6=88=90=E5=99=A8=20generator?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- 19.generator.md | 46 ++++++++++++++++++++++++++++++++++++++++++++++ README.MD | 4 +++- 2 files changed, 49 insertions(+), 1 deletion(-) create mode 100644 19.generator.md diff --git a/19.generator.md b/19.generator.md new file mode 100644 index 0000000..9cfaf52 --- /dev/null +++ b/19.generator.md @@ -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(); +``` \ No newline at end of file diff --git a/README.MD b/README.MD index 525295f..0fe29f7 100644 --- a/README.MD +++ b/README.MD @@ -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) \ No newline at end of file +* [类](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) \ No newline at end of file