Monday, October 11, 2021

JS Promises - Execution Order and Timing

As long as I've been working with JS (just look at how old this blog is to begin getting an idea), I've continued to struggle with execution order and wanted to get it clear in my head. The following helped me do that so I wanted to share.


console.time('full execution');
console.time('code block');
function showExecutionOrder(parm) {
    console.time('outside promise');
    new Promise((resolvereject=> {
        console.time('inside promise');
        resolve(parm);
        console.timeEnd('inside promise');
    }).then((data=> {
        // Lookup mdn and invoke the account sync as required
        console.log({ data });
    });
    console.timeEnd('outside promise');
}
console.time('function call');
showExecutionOrder({ foo: true });
console.timeEnd('function call');
console.timeEnd('code block');
console.timeEnd('full execution');


Update: Another demonstration, in another context:  https://gist.github.com/rainabba/6847b06bff1f5a37bb19663c7a4e3c0e

Followers