如何解决奇怪的承诺链案例:then() 参数未定义,最后一条链数据未返回
首先,由于以下原因,无法在这里公开我的原始代码,我深表歉意:
- 太长了。
- 它包含敏感的商业信息。
但是,我相信以下大纲应该足以描述我的 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 resolve(batchResult);
,而resolve(...)
函数返回的是undefined
。
您的问题是由 explicit-construction anti-pattern 引起的。
- 删除
return new Promise((resolve,reject) => {
(以及匹配的});
。 - 不要调用
resolve
,只需返回您想要用来解决承诺的值 (batchResult
)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。