https://bigfrontend.dev/quiz/4-Promise-then-callbacks-II
What does the code snippet below output by console.log
?
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);
});
Promise.resolve(1)
.then((val) => {
console.log(val); // 1
return val + 1;
})
.then((val) => {
console.log(val); // 2
})
.then((val) => {
console.log(val); // undefined
return Promise.resolve(3).then((val) => {
console.log(val); // 3
});
})
.then((val) => {
console.log(val); // undefined
return Promise.reject(4);
})
.catch((val) => {
console.log(val); // 4
})
.finally((val) => {
console.log(val); // undefined
return 10;
})
.then((val) => {
console.log(val); // undefined
});
-
Promise.prototype.then()
returns aPromise
. If athen
handler:-
returns a value, the
Promise
returned byPromise.prototype.then()
gets resolved with the returned value. -
doesn't return anything, the
Promise
returned byPromise.prototype.then()
gets resolved with anundefined
value. -
returns an already fulfilled
Promise
, thePromise
returned byPromise.prototype.then()
gets resolved with thatPromise
's value as its value. -
returns an already rejected
Promise
, thePromise
returned byPromise.prototype.then()
gets rejected with thatPromise
's value as its value. -
returns a pending
Promise
, the resolution/rejection of the promise returned byPromise.prototype.then()
will be subsequent to the resolution/rejection of thePromise
returned by thethen
handler.
-
-
Promise.prototype.finally()
returns aPromise
. Afinally
handler will not receive any argument. In addition, it won't change the resolved value and just pass through it:Promise.resolve(1) .finally(() => { console.log('Promise ready'); return 10; }) .then((value) => { console.log(value); // 1 });
The reason that the final
then
handler in the code snippet above logsundefined
is thatPromise.prototype.catch()
also returns aPromise
and it behaves the same as callingPromise.prototype.then(undefined, onRejected)
. If thecatch
handler beforefinally()
returns a value, then the finalthen
handler would log that value:Promise.reject(1) .catch((value) => { console.log(value); return 3; }) .finally(() => { console.log('Promise ready'); }) .then((value) => { console.log(value); // 3 });