0

I can't get why function in new Promise fires immediately. Shouldn't it be put in Microtask queue and fire after all global code has executed?

Code:

const prom = new Promise((resolve, reject) => {
  console.log("in Promise");
  resolve(20);
});
prom.then((data) => {
  console.log(12312323);
  console.log(data);
});

console.log(77);

Link to code

Output:

in Promise 
77
12312323
20

1 Answers1

2

When you construct a Promise, its task begins execution immediately.

const p = new Promise((resolve) => {
  console.log('in promise');
  resolve("value");
})

Promises are primarily useful for asynchronous tasks like network requests, and their delayed resolution can make it seem like the execution itself has been deferred, but that's not what's happening.

In this example you can see that there can be a significant delay between when the task starts and when the promise is resolved:

const p = new Promise((resolve) => {
  console.log('first: in promise'); // first
  setTimeout(() => resolve('resolved value'), 2000) // wait 2 seconds before resolving.
})

p.then(val => console.log(`third: ${val}`)); // third

console.log("second: after p.then"); // second
ray
  • 26,557
  • 5
  • 28
  • 27