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