2

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?

dvreed77
  • 2,217
  • 2
  • 27
  • 42

2 Answers2

2

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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • I'm looking at the MDN docs and it says the executor function is called asynchronously: "Typically, it works like this: The operation within executor is asynchronous and provides a callback". Still tryin to grok this – dvreed77 Jan 25 '21 at 17:46
  • 1
    That sentence means that you typically call an async function *inside* the executor not that the executor is itself executed asynchronously. – Felix Kling Jan 25 '21 at 22:04
0

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");
Nick Hyland
  • 357
  • 1
  • 10