3 回答

TA贡献1815条经验 获得超6个赞
当您返回Promise时,您实际上并没有返回Promise内的内容,而是Promise本身。当你说
function api1 () {
return fetch1().then(v =>{
console.log("Api1", v);
return "B"
);
}
您说的是“console.log上一个Promise的结果,然后返回一个包含的新Promise B。
所以当你打电话
api1().then(v => console.log("Api2 call", v));
原始的Promise(包含“ A”)已被使用,新的Promise包含您先前返回的字符串“ B”。
要获得您想要的输出,请像下面这样重写第二部分:
function api1 () {
return fetch1().then(v =>{
console.log("Api1", v);
return v;
);
}

TA贡献1811条经验 获得超6个赞
function fetch1 () {
return new Promise((res, rej) => {
res("A");
});
}
function api1 () {
return fetch1().then(v =>{
console.log("Api1", v);
return "B"
});
}
api1().then(v => console.log("Api2 call", v));
调用时api1().then(v => console.log("Api2 call", v));,api1()将等待fetch1中已解决的承诺被解析,这意味着vin theninapi1函数将等于'A',然后该then函数将'B'返回到下一个,然后theninthen(v => console.log("Api2 call", v));的值v将等于' B'。我希望你明白!

TA贡献1860条经验 获得超9个赞
如您所见,我将返回从fetch1返回的相同值
这实际上是不完全正确,你打电话then后fetch1。那确实有所作为。
使用同步,非承诺代码几乎是相同的。如果返回方法:
return sum(3,7).multiply(2);
您不仅会返回sum(3,7),因为之后您会打来电话multiply(2)。由于multiply通话,该号码将返回20 。
与promise几乎相同,例如:
const myResultPromise = return sumPromise(3,7).then(sumValue => {
return multiplyPromise(2);
})
在这里,这myResultPromise将是20的承诺,因为会将then新的Promise附加到原始sumPromise。
添加回答
举报