javascript - ES6 生成器函数与 Promise

标签 javascript ecmascript-6 es6-promise

如果这个问题太模糊,请告诉我,但是与 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));
   });
}

最佳答案

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

来自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 ,就像在您的示例中一样,但我认为这不是它们的目的。

关于javascript - ES6 生成器函数与 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37792303/

相关文章:

Javascript fetch api,请求的数据类型

javascript - 向 ES6 类动态添加函数的正确方法

javascript - 这在 Mozilla : "let blocks and let expressions are obsolete" 中意味着什么

javascript - Promise.all()被拒绝后的值,显示['' PromiseStatus''] : resolved if catch block is present

javascript - CSS 侧边栏页脚检测

javascript - 如何禁用特定页面上的js脚本?

javascript - 读取 WSDL 并在 javascript 中打印 Web 方法

javascript - Array.from() 与传播语法

javascript - 在一系列 promise 成功或失败后继续

javascript - 使用 Fetch 返回 GitHub 用户数据