Skip to content Skip to sidebar Skip to footer

Using Settimeout With No Timeout Value While Evaluating Result Of Promise.all

The Promise.all MDN docs contain an example of evaluating multiple Promise.all results, but within a setTimeout function without a timeout value. From the docs: // this will be cou

Solution 1:

setTimeout called with no delay value just puts the passed in function on the queue to be executed by the JavaScript event loop. That is usually the next tick, although there could be other things on the queue already scheduled, so the function will be after those.

Promise resolution gets scheduled similarly by putting it on the queue. That means setTimeout will schedule the function completion immediately after the promises are finalized. In turn, this means that the value of p, p2, and p3 will be pending in the current run of the JavaScript event loop, then in the final state when the function delayed by setTimeout is called.

Demonstrating the flow of the program:

//console.logs from StackOverflow snippets don't print the state of the promise//you can open the browser developer tools and click the button to run the snippet//in order to see that outputvar p = Promise.all([1,2,3]); //<-- a pending promise is created
p.finally(() =>console.log("promise fulfilled", p));

console.log("this call is executed immediately", p); //<-- the same run of the event loopsetTimeout(function() {
    console.log("this call is scheduled to execute in the future", p); //<-- to be executed in a subsequent run of the loop.
});

Solution 2:

In JavaScript promises have a higher priority than timeouts so in theory they should all be fulfilled and ready to be logged by the time the function in the timeout is executed.

Post a Comment for "Using Settimeout With No Timeout Value While Evaluating Result Of Promise.all"