您的位置:首页 > 其它

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 with
function*
.

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:

*
yield
is 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