ES6 生成器函数 vs Promises

ES6 Generator Function vs Promises

如果这个问题太模糊,请告诉我,但是使用 ES6 生成器函数与 promises 相比有什么优势?我目前看不到优势,希望有人能对此有所启发。

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

/* 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));
   });
}

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

来自MDN Iterator and generators page

Processing each of the items in a collection is a very common operation. JavaScript provides a number of ways of iterating over a collection, from simple for loops to map() and filter(). Iterators and Generators bring the concept of iteration directly into the core language and provide a mechanism for customizing the behavior of for...of loops.

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

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