What will be the order of the following code:
Promise.resolve(1)
.then((val) => {
console.log(val);
return val + 1;
})
.then((val) => {
console.log(val);
})
.then((val) => {
console.log(val);
return Promise.resolve(3).then((val) => {
console.log(val);
});
})
.then((val) => {
console.log(val);
return Promise.reject(4);
})
.catch((val) => {
console.log(val);
})
.finally((val) => {
console.log(val);
return 10;
})
.then((val) => {
console.log(val);
});
1
2
undefined
3
undefined
4
undefined
undefined
Here's why:
1
- First promise resolves with 12
- Second .then gets 1+1undefined
- Third .then gets undefined (since previous .then had no return)3
- From the nested Promise.resolve(3)undefined
- Next .then gets undefined (nested promise had no return)4
- From Promise.reject(4) caught in catchundefined
- From finally (finally always receives undefined)undefined
- Last .then gets undefined (finally's return value is ignored)Key points:
undefined
undefined
and its return value is ignored