0

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.

  • 3
    `console.log` has no return value. From the first `then` on there is nothing but undefined being passed to the next then. – pilchard May 15 '23 at 07:43
  • Possibly a duplicate of [*What is the difference between a function call and function reference?*](https://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference) – T.J. Crowder May 15 '23 at 07:57

2 Answers2

0

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 undefined

A2) .then(()=>console.log) at this point you dont call the function

Zokki
  • 125
  • 1
  • 8
0

.then(console.log) passes the console.log function into then, 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 is undefined), and so console.log outputs undefined. (The fulfillment value is undefined because the promise was created by .then(() => console.log(11)), which fulfills its promise with the result of calling console.log, which is always undefined.)

.then(() => console.log) passes an arrow function into .then instead. When that function is called, it returns console.log (the function) without calling it. Nothing ever calls it, and so you don't see undefined.

This doesn't have anything to do with promises. It's just the difference between this:

function then(callback) {
    callback(undefined);
}

then(console.log);

and this:

function then(callback) {
    callback(undefined);
}

then(() => console.log);
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875