javascript - 为什么从函数返回的承诺解析为从该函数内部的 .then 返回的值
问题描述
我创建了一个返回承诺的函数。
function fetch1 () {
return new Promise((res, rej) => {
res("A");
});
}
我在函数 api1 中调用此函数并返回从 fetch1 返回的承诺。
function api1 () {
return fetch1().then(v =>{
console.log("Api1", v);
return "B"
);
}
如您所见,我返回的值与从 fetch1 返回的值相同。我没有创造任何新的承诺。但是当我调用它时,我得到以下输出。
api1().then(v => console.log("Api2 call", v));
Api1 A
Api2 call B
我的预期输出应该是
Api1 A
Api2 call A
从这个链接可以看出。然后,这个承诺被束缚了。从 first then 返回的 promise 在 next then 中解决。但是我没有从那时起在 api1 函数中返回任何承诺。
我可以绕过它。但是为什么会发生。
解决方案
When you return a Promise, you don't actually return what's inside the Promise but the Promise itself. When you say
function api1 () {
return fetch1().then(v =>{
console.log("Api1", v);
return "B"
);
}
you're saying "console.log
the result of the previous Promise, then return a new promise containing B
.
So when you call
api1().then(v => console.log("Api2 call", v));
the original Promise (containing "A") has already been consumed and your new Promise contains the string "B" you returned earlier.
To get the output you intended, rewrite your second section like this:
function api1 () {
return fetch1().then(v =>{
console.log("Api1", v);
return v;
);
}
推荐阅读
- visual-studio - Gulp 错误缺少脚本:在 MVC 项目中构建
- java - 在使用 Spring Boot 进行集成测试期间使用测试数据填充数据库
- assembly - 编写 Microsoft Fastcall 64 位汇编函数
- c++ - 如何用 0x00 覆盖所有可用磁盘空间?
- google-sheets - 试图将“增长率”添加到谷歌表格
- javascript - 赛普拉斯 cy.write 将新项目推送到数组会引发“推送不是函数”错误
- python - 调用 Fortran Intel MKL dgemm 与 numpy 以及与 matmul 的函数性能不佳
- amazon-web-services - AWS Kinesis Firehose 是否在数据传输期间提供完整性控制?
- docker - 如何在 docker 中部署带有静态文件的 Web 应用程序?
- python - 无法弄清楚为什么 PyDub 不起作用