【发布时间】:2016-10-14 00:32:33
【问题描述】:
如果这个问题太模糊,请告诉我,但是使用 ES6 生成器函数与 Promise 相比有什么优势?我目前看不到优势,希望有人能对此有所了解。
例如,以异步方式检索数据时:
/* 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));
});
}
【问题讨论】:
-
它很模糊。你能展示一下你会如何使用它们来做类似的事情吗?
-
没问题,加个例子。
标签: javascript ecmascript-6 es6-promise