-1

I was reading into javascript promises in depth. I came across one fundamental issue with my understanding.

Here is the piece of code :

let p = new Promise(function (resolve, reject) {
  let a = true
  if (a) {
   resolve(console.log("a was true"));
  } else reject("a was false")
})

Why the above piece of code immediately logs an a was true even if I haven't called it as such:

p.then((msg) => {
  return msg
})

However,The following piece of code only logs the value with .then() calls

let p = new Promise(function (resolve, reject) {
  let a = true
  if (a) {
    resolve("a was true")
  } else reject("a was false")
})

p.then((msg) => {
  console.log(msg)
}).catch((msg) => {
  console.log(msg)
})


If someone can point out, why the very first piece of code doesnt need a .then() chain and does an early logs?

Please Note, I understand this is not async code, its for demo purpose only.

anshul
  • 661
  • 9
  • 27

1 Answers1

2

The promise executor is executed immediately, even if you don't .then the promise.

Your first code is equivalent to

let p = new Promise(function (resolve, reject) {
  let a = true
  if (a) {
    let value = console.log('a was true');
    resolve(value);
  } else reject('a was false')
})

and as you know, console.log() logs the string as a side effect and returns undefined, so the resolved value of that promise is undefined.

In your second example, the resolved value of the promise is the string "a was true", and nothing is logged as a side effect.

AKX
  • 152,115
  • 15
  • 115
  • 172