Promise is not immediately returned for function

Viewed 69

I was trying to come up with a simple example to show how promises get around a blocking call, but this example isn't working the way I expect

function blockForLoopPromise() {
  return new Promise((resolve, reject) => {
    for (let i = 0 ; i < 10000000000 ; i++) {
      
    }
    resolve("done")
  })
}

blockForLoopPromise().then(() => console.log("DONE!"))
console.log("END")

In this example, "END" is not called until the long for loop is completed. Shouldn't it be called immediately?

2 Answers

Shouldn't it be called immediately?

No. The function you pass to the Promise constructor is called synchronously.

From MDN:

A function to be executed by the constructor, during the process of constructing the new Promise object.

You can also see in the specification that the function is called immediately by the constructor (step 9).

You can update to the following to get the behaviour you're looking for. setImmediate is used in node to execute the function on the next iteration of the event loop

function blockForLoopPromise() {
  return new Promise((resolve, reject) => {
    setImmediate(() => {
      for (let i = 0 ; i < 10000000000 ; i++) {
      
      }
      resolve("done")
    });
  });
}

blockForLoopPromise().then(() => console.log("DONE!")); 
console.log("END");
Related