Search code examples
javascriptasynchronousasync-awaitpromise

Why does the console.log output during instantiation of a Promise object, but does not output when a ".then()" is called on it?


const promise = new Promise((resolve, reject) => {
  console.log("working 1.0")
  setTimeout(() => {
    console.log("working 2.0")
    resolve([90, 70, 55]);
  }, 7000);
});
console.log("Hi")
promise.then(values => {
  console.log(values[1]);
});

This is the output that I get:

working 1.0
Hi
working 2.0
70

But why isn't it:

working 1.0
Hi
working 1.0
working 2.0
70

My idea being, since we are finally doing .then, wouldn't the entire function that I initialized inside of new Promise() be called ?

Thank you for your help!


Solution

  • The function you pass to new Promise() is called immediately and it is called once. new Promise() then returns a promise object.

    The function you pass to then is called after the promise resolves. It is passed the resolved value of the promise.

    Calling then doesn't affect the function previously passed to new Promise().