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();
Should output 29 to the console but it’s not work.
2
Answers
As others have mentioned before me the issue with your chaining is that you are losing the context of the previous result. So you can either use
async/await
orPromise.all
Here is the
async/await
syntax which leaves the code more readableYou can also use
Promise.all
like thisIf you want to use async/await other answers show the correct code. I think what you might be trying to get is: