如何使用承诺链重写此代码?



function getSmth(num) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num * num), 500)
});
}
function func() {
getSmth(2).then(res1 => {
getSmth(3).then(res2 => {
getSmth(4).then(res3 => {
console.log(res1 + res2 + res3);
});
});
});
}
func();

function getSmth(num) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num * num), 500)
});
}
function func() {
getSmth(2)
.then(res1 => getSmth(3))
.then(res2 => getSmth(4))
.then(res3 => {
console.log(res1 + res2 + res3);
})
}
func();

应该输出29到控制台,但它不工作。

如果您想使用async/await其他答案请显示正确的代码。我想你可能想要得到的是:

function func() {
getSmth(2)
.then(result => getSmth(3).then(res2 => result + res2))
.then(result => getSmth(4).then(res3 => result + res3))
.then(result => {
console.log(result);
})
}

正如其他人在我之前提到的那样,您的链接的问题是您正在丢失先前结果的上下文。所以你可以用async/awaitPromise.all

下面是async/await语法,它使代码更具可读性

function getSmth(num) {
return new Promise((resolve, reject) => {
setTimeout(() => resolve(num * num), 500)
});
}
async func(){
const res1 = await getSmth(2);
const res2 = await getSmth(3); 
const res3 = await getSmth(4);
console.log(res1 + res2 +res3);
}
func().then(()=>{})

您也可以像这样使用Promise.all


Promise.all([getSmth(2), getSmth(3), getSmth(4)])
.then( results => console.log(results[0] + results[1] + results[2]);

相关内容

  • 没有找到相关文章