skip to Main Content

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


  1. 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

    Login or Signup to reply.
  2. .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);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search