前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >ES6特性-Generators

ES6特性-Generators

作者头像
贺贺V5
发布2018-08-21 12:02:37
2390
发布2018-08-21 12:02:37
举报

what

你可以将Generators认为是可以中断进程、恢复进程的代码段,like this:

代码语言:javascript
复制
function* genFunc() {
    // (A)
    console.log('First');
    yield;
    console.log('Second');
}
  • function*是一个新的Generators函数的关键字。
  • yield是一个可以暂停它自己的操作符。
  • Generators还可以通过yield接收和发送。
  • 当调用生成器函数genFunc()时,您将获得可用于控制进程的生成器对象genObj:
代码语言:javascript
复制
const genObj = genFunc();

Generators的概念

Generators are defined with function*.

代码语言:javascript
复制
function* foo(x) {
    yield x + 1;

    var y = yield null;
    return x + y;
}

结果:

代码语言:javascript
复制
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,我就很不解,然后找了找资料,才得知:

<u·var y = yield; or var yield null;使用来接收.next(参数)方法中的参数的,也就是:这个参数传入生成器中,作为上一个阶段异步任务的返回结果,被函数体内的变量y接收。</u>

另外一个例子:

代码语言:javascript
复制
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));

结果:

代码语言:javascript
复制
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:
代码语言:javascript
复制
function* genFunc() { ··· }
 const genObj = genFunc();
  • Generator function expressions:
代码语言:javascript
复制
 const genFunc = function* () { ··· };
 const genObj = genFunc();
  • Generator method definitions in object literals:
代码语言:javascript
复制
 const obj = {
     * generatorMethod() {
         ···
     }
 };
 const genObj = obj.generatorMethod();
  • Generator method definitions in class definitions (class declarations or class expressions):
代码语言:javascript
复制
 class MyClass {
     * generatorMethod() {
         ···
     }
 }
 const myInst = new MyClass();
 const genObj = myInst.generatorMethod();

特性

  • 实现迭代
  • 简化异步代码
代码语言:javascript
复制
function fetchJson(url) {
    return fetch(url)
    .then(request => request.text())
    .then(text => {
        return JSON.parse(text);
    })
    .catch(error => {
        console.log(`ERROR: ${error.stack}`);
    });
}

上下是等价的

代码语言:javascript
复制
// 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如何工作

代码语言:javascript
复制
function* genFunc() {
    yield 'a';
    yield 'b';
}

调用结果:

代码语言:javascript
复制
> 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不能在回调函数中使用。
代码语言:javascript
复制
function* genFunc() {
    ['a', 'b'].forEach(x => yield x); // SyntaxError
}

function* genFunc() {
    for (const x of ['a', 'b']) {
        yield x; // OK
    }
}

参考

写在后面

GitHub上集大家之力搞了一个前端面试题的项目,里面都是大家面试时所遇到的题以及一些学习资料,有兴趣的话可以关注一下。如果你也有兴趣加入我们的话,请在项目中留言。项目同时也可以在gitbook上查看。

InterviewLibrary-GitHub InterviewLibrary-gitbook

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.05.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • what
  • Generators的概念
  • Generators的类型
  • 特性
  • Generator扮演的角色
  • yield如何工作
  • 参考
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档