I have the following code:
function asyncLoop() {
return new Promise(function(res, rej) {
for(let i=0;i<=400000000;i++) {
if(i===400000000) {console.log("done"); res();}
}
});
}
asyncLoop().then(()=>{console.log("then")});
console.log("out");
I am getting the following output:
done
out
then
According to my understanding of Promises, the asyncLoop should have run asynchronously and the following should have been the output:
out
done
then
What am I missing?
then()is guaranteed to be called asynchronously even if the promise is already resolved.then()handler is called and it has nothing to do with what the OP was confused with in this question as we can see by your own answer. People somehow think that promises can magically change a synchronous operation into an asynchronous operation. They don't do that. Yes,.then()is called on the next tick, but that doesn't change at all when the actual code before it is executed. If it was synchronous, it's still synchronous. That's the point to the OP.