ES6特性-Generators
2017-05-27 18:56
316 查看
what
你可以将Generators认为是可以中断进程、恢复进程的代码段,like this:function* genFunc() { // (A) console.log('First'); yield; console.log('Second'); }
function*是一个新的Generators函数的关键字。
yield是一个可以暂停它自己的操作符。
Generators还可以通过
yield接收和发送。
当调用生成器函数
genFunc()时,您将获得可用于控制进程的生成器对象genObj:
const genObj = genFunc();
Generators的概念
Generators are defined withfunction*.
function* foo(x) { yield x + 1; var y = yield null; return x + y; }
结果:
var gen = foo(5); gen.next(); // { value: 6, done: false } gen.next(); // { value: null, done: false } gen.send(2); // { value: 7, done: true }
把这个方法贴到在线编辑器上运行了一下,打印出来的的
y = 2,我就很不解,然后找了找资料,才得知:
function* foo(x) { yield x+1; var y = yield; console.log(`y=${y}`); return x + y ; } var gen = foo(5); console.log(gen.next()); console.log(gen.next()); console.log(gen.next(4));
结果:
Object { "done": false, "value": 6 } Object { "done": false, "value": undefined } "y=4" Object { "done": true, "value": 9 }
Notes:
*
yieldis allowed anywhere an expression is. This makes it a powerful construct for pausing a function in the middle of anything, such as foo(yield x, yield y), or loops.
* Calling a generator looks like a function, but it just creates a generator object. You need to call next or send to resume the generator. send is used when you want to send values back into it. gen.next() is equivalent to gen.send(null). There’s also gen.throw which throws an exception from within the generator.
* Generator methods don’t return a raw value, they return an object with two properties: value and done. This makes it clear when a generator is finished, either with return or simply the end of the function, instead of a clunky StopIteration exception was the old API.
-- 翻译的不好,直接上原文。
Generators的类型
Generator function declarations:function* genFunc() { ··· } const genObj = genFunc();
Generator function expressions:
const genFunc = function* () { ··· }; const genObj = genFunc();
Generator method definitions in object literals:
const obj = { * generatorMethod() { ··· } }; const genObj = obj.generatorMethod();
Generator method definitions in class definitions (class declarations or class expressions):
class MyClass { * generatorMethod() { ··· } } const myInst = new MyClass(); const genObj = myInst.generatorMethod();
特性
实现迭代简化异步代码
function fetchJson(url) { return fetch(url) .then(request => request.text()) .then(text => { return JSON.parse(text); }) .catch(error => { console.log(`ERROR: ${error.stack}`); }); }
上下是等价的
// es6 const fetchJson = co.wrap(function* (url) { try { let request = yield fetch(url); let text = yield request.text(); return JSON.parse(text); } catch (error) { console.log(`ERROR: ${error.stack}`); } }); // ECMAScript 2017 async function fetchJson(url) { try { let request = await fetch(url); let text = await request.text(); return JSON.parse(text); } catch (error) { console.log(`ERROR: ${error.stack}`); } }
Generator扮演的角色
Iterators - 数据生成器每一个
yield都可以通过
next()返回一个数据,所以可以通过循环或者递归生成很多数据。
Observers - 数据消费者
yield可以通过
next()返回数据,那么就可以在收到下一个数据之前暂停,来消费这些数据,然后再恢复继续接收数据。
Coroutines - 数据生成器和数据消费者
yield如何工作
function* genFunc() { yield 'a'; yield 'b'; }
调用结果:
> const genObj = genFunc(); > genObj.next() { value: 'a', done: false } > genObj.next() { value: 'b', done: false } > genObj.next() // done: true => end of sequence { value: undefined, done: true }
yield不能在回调函数中使用。
function* genFunc() { ['a', 'b'].forEach(x => yield x); // SyntaxError } function* genFunc() { for (const x of ['a', 'b']) { yield x; // OK } }
参考
Generators相关文章推荐
- ES6新特性之 promise
- 【javascript】ES6 特性 菜鸟学习笔记
- ES6(函数新增特性)
- ES6新特性三: Generator(生成器)函数详解
- ES6新特性 Class的实现
- ES6新特性
- ES6新特性:使用export和import实现模块化
- 【微信小程序+ES6新特性应用】通过对类的操作来处理数据后显示在视图界面
- ES6部分特性学习
- IE12四大特性:网络音频、媒体捕获、ES6 Promises和HTTP/2
- es6开发:总结归纳es6的十大特性
- ES6新特性:Generator以及衍生NPM库CO入门
- JavaScript中的Reflect对象详解(ES6新特性)
- # 利用es6的新特性巧妙实现JavaScript中的数组求最大值问题
- ES6的特性(译+注解)
- 【前端知识点】30分钟了解ES6最新核心特性
- ES6新特性之解构、参数、模块和记号用法示例
- ES6新特性:解构赋值
- ES6新特性四:变量的解构赋值实例
- Atitit js版本es5 es6新特性