Why wrapping your code in resolved prop makes your sync code act like async code?

Viewed 94

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???

2 Answers

Couple of things you need to understand here:

  1. Promises don't make something asynchronous - they are a notification mechanism for something that's already asynchronous. Promises notify you of the success or failure of an operation that's already asynchronous.

    Callback function of the promise constructor is called synchronously; it is called synchronously to start an operation that's already asynchronous.

    In your case, promise constructor contains synchronous code; this is why it blocks other code.

  2. Moving the loop inside the callback function of then executes the loop asynchronously because the callback function of then is invoked asynchronously.

    Note: Even though the callback function of then method is invoked asynchronously, once it starts executing, no other code will execute until the synchronous code inside the callback is executed completely.

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.

Related