美文网首页
es6(Generator)

es6(Generator)

作者: 余生筑 | 来源:发表于2017-10-27 08:54 被阅读8次

参考资料

遍历器(Iterator)

  • 它是一种接口,为各种不同的数据结构提供统一的访问机制。
  • 任何数据结构只要部署Iterator接口,就可以完成内部遍历操作
  • 一个数据结构只要具有Symbol.iterator属性,就可以认为是“可遍历的”(iterable)
const obj = {
  [Symbol.iterator] : function () {
    return {
      next: function () {
        return {
          value: 1,
          done: true
        };
      }
    };
  }
};

Generator

  • 语法
function* helloWorldGenerator() {
  yield 'hello';
  yield 'world';
  return 'ending';
}

var hw = helloWorldGenerator();
hw.next()
// { value: 'hello', done: false }

hw.next()
// { value: 'world', done: false }

hw.next()
// { value: 'ending', done: true }

hw.next()
// { value: undefined, done: true }
  • throw()
var g = function* () {
  try {
    yield;
  } catch (e) {
    console.log('内部捕获', e);
  }
};

var i = g();
i.next();

try {
  i.throw('a');
  i.throw('b');
} catch (e) {
  console.log('外部捕获', e);
}
// 内部捕获 a
// 外部捕获 b
  • 异步应用
    ES6 诞生以前,异步编程的方法,大概有下面四种。
    1.回调函数
    2.事件监听
    3.发布/订阅
    4.Promise 对象
    Generator 函数将 JavaScript 异步编程带入了一个全新的阶段。

Callback下的异步操作

function getA(callback)
{
//getA任务代码
callback()
}
function getB()
{
//getB任务代码
}
getA(getB)

Generator 下的异步操作

function* async(getA,getB)
{
yield getA()
yield getB()
}
function getA()
{
//getA任务代码
}
function getB()
{
//getB任务代码
}
var a=async()
a.next()
a.next()

相关文章

网友评论

      本文标题:es6(Generator)

      本文链接:https://www.haomeiwen.com/subject/xgzxpxtx.html