Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading