在ES6 Promise中链接.then()调用 [英] Chaining .then() calls in ES6 promises
问题描述
我认为使用ES6 Promises时应该可以链接.then()方法。换句话说,我认为当一个Promise被解决时,传递给resolve函数的值应该传递给任何链接的 then 处理程序。如果是这样的话, value 为何在下面的链接 then 处理程序中返回未定义?
I thought it was supposed to be possible to chain the .then() method when using ES6 Promises. In other words I thought that when a promise is resolved the value passed to the resolve function should be passed to any chained then handlers. If this is so how come value comes back undefined in the chained then handler below?
function createPromise() {
return new Promise((resolve) => {
resolve(true);
});
}
createPromise()
.then((value) => {
console.log(value); // expected: true, actual: true
})
.then((value) => {
console.log(value); // expected: true, actual: undefined
});
推荐答案
每个 then()
可以返回一个值,该值将用作下一个 then()
调用的解析值。在您的第一个 then()
中,您什么都不返回,因此在下一个回调中未定义 value
。在第一个中返回 value
使其在第二个中可用。
Each then()
can return a value that will be used as the resolved value for the next then()
call. In your first then()
, you don't return anything, hence value
being undefined in the next callback. Return value
in the first one to make it available in the second.
function createPromise() {
return new Promise((resolve) => {
resolve(true);
});
}
createPromise()
.then((value) => {
console.log(value); // expected: true, actual: true
return value;
})
.then((value) => {
console.log(value); // expected: true, actual: true
});
这篇关于在ES6 Promise中链接.then()调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!