Loop inside of the promise works like sync code, for example:
console.log('im working')
function proLoop(){
return Promise((resolve ,rejects)=>{
for (let i = 0; i < 1000000000000; i++) {}
console.log('loop is done')
})
}
proLoop();
console.log('im working')
So even if we write is like promise it will get more time and freezes our code In other words it will works synchronically.
i find a solution but why it works?
so the solution is just warp your code as like resolved promise
like this
return new Promise.resolve().then( ()=>{
for (let i = 0; i < 1000000000000; i++) {}
console.log('loop is done')
})
but why and how???
In both cases, the for
loop will block the main event loop. The difference is when the for
loop starts.
In the first case, the function passed to new Promise
is executed immediately. It therefore blocks the rest of the function that creates it.
In the second case, the function passed to then()
is queued up to run next time the event loop is free. The function that created it therefore finishes first and then the for
loop runs. (If that's the goal, then its a pretty unintuitive approach, and using setImmediate
(in browsers) or Node's process.nextTick()
would be neater.)
If you wanted to shunt the work done by the for
loop off the main event loop so it didn't block anything you would use a Web Worker or Worker thread depending on what JavaScript runtime you were using.