請讓我知道這是否太模糊的問題,但使用ES6發電機功能與承諾相比有什麼優勢?我目前看不到優勢,希望有人能夠對此有所瞭解。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));
});
}
它非常含糊。你能否展示你將如何使用它們來做類似的事情? – 4castle
沒問題,會添加一個例子。 –