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?