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

Time:02-25

Loop inside of the promise works like sync code, for example:


console.log('im working')
function proLoop(){
    return new 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 Promise.resolve().then( ()=>{
    for (let i = 0; i < 1000000000000; i  ) {}
    console.log('loop is done')
})

but why and how???

CodePudding user response:

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.

CodePudding user response:

executor function inside Promise is called synchronously before the return of the Promise Object. That's why the loop is executed before the last line.

Please have a look at the example below.

Promise.resolve("line 1").then(res => console.log(res));

console.log("line 2");

new Promise((resolve, rejects) => {
    console.log("line 3: inside executor");
});

console.log("line 4");

  • Related