Q1.) Why I am getting undefined if i pass console.log in then block in a promise chian?
new Promise((resolve, reject) => {
console.log(4)
resolve(5)
console.log(6)
}).then(() => console.log(7))
.catch(() => console.log(8))
.then(() => console.log(9))
.catch(() => console.log(10))
.then(() => console.log(11))
.then(console.log)
.finally(() => console.log(12))
Output:
4
6
7
9
11
undefined
12
Q2.) However if I pass console.log in then block using arrow function, i get nothing as output wrt that then block.
new Promise((resolve, reject) => {
console.log(4)
resolve(5)
console.log(6)
}).then(() => console.log(7))
.catch(() => console.log(8))
.then(() => console.log(9))
.catch(() => console.log(10))
.then(() => console.log(11))
.then(()=>console.log)
.finally(() => console.log(12))
Output:
4
6
7
9
11
12
Can anyone explain this behaviour?
I am just curious to understand this behaviour of our beloved JS.
2
Answers
A1)
.then(() => console.log(11))
is the same as.then(() => { return console.log(11) })
and console.log returns void/undefined-> so you log in the line
.then(console.log)
the returnvalue from the last one and this is undefinedA2)
.then(()=>console.log)
at this point you dont call the function.then(console.log)
passes theconsole.log
function intothen
, telling it to call that function when the promise you called.then
on is fulfilled. When that happens, it will be passed the fulfillment value (in this case, that value isundefined
), and soconsole.log
outputsundefined
. (The fulfillment value isundefined
because the promise was created by.then(() => console.log(11))
, which fulfills its promise with the result of callingconsole.log
, which is alwaysundefined
.).then(() => console.log)
passes an arrow function into.then
instead. When that function is called, it returnsconsole.log
(the function) without calling it. Nothing ever calls it, and so you don’t seeundefined
.This doesn’t have anything to do with promises. It’s just the difference between this:
and this: