为什么 promise 用 undefined 解决? [英] Why is promise resolving with undefined?
问题描述
var firstPromise = new Promise((resolve, reject) => {
resolve('first promise');
});
firstPromise.then(() => {
return new Promise((resolve, reject) => {
resolve('second promise');
}).then((result) => {
console.log('hello');
});
}).then((result) => {
console.log(result);
});
我知道这不是编写此承诺链的最佳方式,但我想知道为什么最后一个 .then
会执行.我没有用 console.log('hello')
返回任何东西,那么第二个承诺的 .then 不会永远解决吗?
I know this is not the best way to write this promise chain, but I was wondering why the last .then
executes at all. I'm not returning anything with console.log('hello')
, so wouldn't the .then off of the second promise never resolve?
推荐答案
因为您已经将多个 promise 链接在一起,并且您的 .then()
处理程序之一不返回任何内容.
Because you've chained several promises together and one of your .then()
handlers returns nothing.
这部分:
.then((result) => {
console.log('hello');
// since there is no return value here,
// the promise chain's resolved value becomes undefined
});
什么都不返回,本质上与return undefined
相同,因此链的解析值变为undefined
.
returns nothing which is essentially the same as return undefined
and therefore the resolved value of the chain becomes undefined
.
您可以将其更改为这样以保留已解析的值:
You can change it to this to preserve the resolved value:
.then((result) => {
console.log('hello');
return result; // preserve resolved value of the promise chain
});
请记住,每个 .then()
处理程序的返回值都会成为链的解析值.没有返回值使得解析值成为undefined
.
Remember that the return value of every .then()
handler becomes the resolved value of the chain going forward. No return value makes the resolved value be undefined
.
这篇关于为什么 promise 用 undefined 解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!