奇怪的 Promise Chaining Case:then() 参数未定义,未返回最后一个链数据
Weird Promise Chaining Case: then() parameter is undefined, last chain data not returned
首先,由于以下原因,未能在这里公开我的原始代码,我深表歉意:
- 太长了。
- 它包含敏感的商业信息。
但是,我相信以下大纲应该足以描述我的 promise 链接代码中发生的一些奇怪的事情(请参阅代码中的注释):
return new Promise((resolve, reject) => {
return somePromiseFunction()
.then(async allAccSummaries => {
// Some very lengthy codes here.
// Contains several await function calls.
let batchResult = {
// Some property assignments here
};
console.log(batchResult); // Confirmed batchResult is NOT undefined.
return resolve(batchResult); // This was the result returned to the caller instead!
})
.then(prevBatchResult => {
console.log(prevBatchResult); // prevBatchResult is undefined, why?
// Some other very lengthy logics here.
let finalBatchResult = {
// Some property assignments here
};
return finalBatchResult; // This was not returned to caller as final result!
}
}
我想知道这怎么可能发生?我知道 then()
参数为 undefined
的唯一原因是前一个 then()
未返回任何内容,但我的情况并非如此。另外,我希望 final then()
的结果返回给调用者,而不是第一个。有人可以向我指出任何可能导致这种情况发生的可能性吗?提前致谢!
console.log(prevBatchResult); // prevBatchResult is undefined, why?
因为前面then()
函数的return值为return resolve(batchResult);
而resolve(...)
函数returns undefined
.
您的问题是由explicit-construction anti-pattern引起的。
- 删除
return new Promise((resolve, reject) => {
(以及匹配的 });
.
- 不要调用
resolve
只是 return 您要用来解析承诺的值 (batchResult
)。
首先,由于以下原因,未能在这里公开我的原始代码,我深表歉意:
- 太长了。
- 它包含敏感的商业信息。
但是,我相信以下大纲应该足以描述我的 promise 链接代码中发生的一些奇怪的事情(请参阅代码中的注释):
return new Promise((resolve, reject) => {
return somePromiseFunction()
.then(async allAccSummaries => {
// Some very lengthy codes here.
// Contains several await function calls.
let batchResult = {
// Some property assignments here
};
console.log(batchResult); // Confirmed batchResult is NOT undefined.
return resolve(batchResult); // This was the result returned to the caller instead!
})
.then(prevBatchResult => {
console.log(prevBatchResult); // prevBatchResult is undefined, why?
// Some other very lengthy logics here.
let finalBatchResult = {
// Some property assignments here
};
return finalBatchResult; // This was not returned to caller as final result!
}
}
我想知道这怎么可能发生?我知道 then()
参数为 undefined
的唯一原因是前一个 then()
未返回任何内容,但我的情况并非如此。另外,我希望 final then()
的结果返回给调用者,而不是第一个。有人可以向我指出任何可能导致这种情况发生的可能性吗?提前致谢!
console.log(prevBatchResult); // prevBatchResult is undefined, why?
因为前面then()
函数的return值为return resolve(batchResult);
而resolve(...)
函数returns undefined
.
您的问题是由explicit-construction anti-pattern引起的。
- 删除
return new Promise((resolve, reject) => {
(以及匹配的});
. - 不要调用
resolve
只是 return 您要用来解析承诺的值 (batchResult
)。