0

Following is a demo:

var forever = new Promise(function (resolve, reject) {
  while (true) {
  }
  resolve("done")

});
console.log("Promise returned")

The console.log("Promise returned") will never be executed. It seems that the evaluate of forever will block the thread and never return.

Wrap the function body into a setTimeout fixed this issue:

var forever = new Promise(function (resolve, reject) {
  setTimeout(function() {
    while (true) {
    }
    resolve("done")
  },0)

});
console.log("Promise returned")

Shouldn't the callback parameter of Promise be deferred to be execute (no need to be wrapped by setTimeout)? Is there any documentation about this behavior?

Hanfei Sun
  • 45,281
  • 39
  • 129
  • 237
  • No. If you wrap a function that makes an ajax call in a Promise, is it going to defer making the call over the network? – Jared Smith Apr 06 '16 at 16:41
  • 1
    No, there's no reason to defer the executor. Yes, this is documented; I'll search for the dupe. The lesson is that you should not put infinite loops in your code. – Bergi Apr 06 '16 at 16:41
  • What's the point of this code? Creating a promise that never resolves can be done *a lot* easier. – Tomalak Apr 06 '16 at 16:42

2 Answers2

3

Section 25.4.3.1 of the spec states that "when the Promise function is called with argument executor" the following steps are taken:

  1. Let completion be Call(executor, undefined, «resolvingFunctions.[[Resolve]], resolvingFunctions.[[Reject]]»).

Thus, the spec requires that the callback to a Promise constructor be called during construction. MDN notes this as well:

The executor function is executed immediately.

The executor function does not necessarily need to call resolve or reject immediately, but is itself called before new Promise returns.

ssube
  • 47,010
  • 7
  • 103
  • 140
0

The function passed to new Promise() is called synchronously. It may call other async functions, and resolve (or reject) the promise within the callbacks of those functions, but if you do while (true) directly within that top-level function it will immediately block the browser.

Alnitak
  • 334,560
  • 70
  • 407
  • 495