ES6生成器函数与承诺

时间:2016-06-13 14:26:09

标签: javascript ecmascript-6 es6-promise

如果问题太含糊,请告诉我,但使用ES6生成器功能与承诺相比有什么好处?我目前看不到这种优势,希望有人可以对此有所了解。

例如,以异步方式检索数据时:

/* Using promises */
fetch('api-endpoint')
   .then( resp => response.json() )
   .then( name => obj.name)
   .then( x => console.log('Name: ', name) )

//VS

/* As a generator function and assuming we have required node-fetch */
run(function *() {
   const url = 'api-endpoint';
   const resp = yield fetch(url);
   const obj = yield response.json();
   const name = yield obj.name;
   console.log("Name available here: ", name); 
}

function run(genFunc) {
   const iterator = genFunc();
   const iteration = iterator.next();
   const promise = iteration.value();
   promise.then( x => {
      const additionalIterator = iterator.next(x);
      const additionalPromise = iterator.value;
      additionalPromise.then( y => iterator.next(y));
   });
}

1 个答案:

答案 0 :(得分:2)

Promises处理异步事件,而生成器提供了一个强大的工具来编写维护自己状态的循环和算法。

来自MDN Iterator and generators page

  

处理集合中的每个项目非常常见   操作。 JavaScript提供了许多迭代方法   集合,从简单的for循环到map()和filter()。迭代器和   生成器将迭代的概念直接带入核心   语言并提供自定义行为的机制   for ... of loops。

所以我认为它们旨在解决两个截然不同的问题。

话虽如此,you could use generators instead of promises,就像你的例子一样,但我并不认为这是他们的目的。

相关问题