首页 > 解决方案 > 为什么从函数返回的承诺解析为从该函数内部的 .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 函数中返回任何承诺。

我可以绕过它。但是为什么会发生。

标签: javascriptpromise

解决方案


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;
 );
}

推荐阅读