In my project I have a very long running operation, so I decided to put it in a Promise
because I thought that in this way I could continue to execute the other operations while the code inside the Promise
was running.
While debugging, I find out that the code outside the Promise
executed only when the code inside the Promise
finished executing.
Here is an example of what I'm doing in my project (it simulates a long operation, so it takes a while):
new Promise(function(resolve, reject) {
var i = 0;
while (i < 1000000000) {
i++
}
console.log("Executing inside Promise");
});
console.log("Executing outside Promise");
I am not really sure why this is happening and that's why I asked it. But I think that it is somehow related to the fact that the code inside the Promise
is synchronous.
Indeed when it is async (i.e. the setTimeout()
method) it runs after the outside code finishes executing.
new Promise(function(resolve, reject) {
setTimeout(function() {
var i = 0;
while (i < 1000000000) {
i++
}
console.log("Executing inside Promise");
}, 3000)
});
console.log("Executing outside Promise");
But I still can't figure out why the code inside the Promise
is executing synchronously?
Shouldn't it execute asynchronously?