I am struggling to understand why an asynchronous function with some calculations takes such a long time to execute. I have simplified my code like so:
const syncCalc = () => {
let v = 0;
for (let i = 1; i < 10000000; i++) {
//emtpy loop
v += i
}
return v;
}
const asyncCalc = () =>
new Promise(resolve => {
let v = 0;
for (let i = 1; i < 10000000; i++) {
//emtpy loop
v += i
}
resolve(v);
})
console.time('syncCalc');
console.log("Result:", syncCalc());
console.timeEnd('syncCalc');
console.log('------------')
console.time('asyncCalc');
asyncCalc().then(v => console.log("Result:", v));
console.timeEnd('asyncCalc');
The result of the above code run in node is:
Result: 49999995000000
syncCalc: 27.659ms
------------
asyncCalc: 14.152ms
Result: 49999995000000
The first part (i.e. 27 ms) makes perfect sense. It takes a while for the calculation to finish in a synchronous environment.
What I don’t get is why it takes 14 ms to get past the asyncCalc
function. Shouldn’t the jump from console.time('asyncCalc');
to console.timeEnd('asyncCalc');
be instant as we DO NOT wait for the asyncCalc().then(...
to execute?
Why, then, does this take under a millisecond to get from time
to timeEnd
?
const asyncTimeout = () =>
new Promise(resolve => {
setTimeout(() => resolve(49999995000000), 1000)
})
console.time('asyncCalc');
asyncTimeout().then(v => console.log("Result:", v));
console.timeEnd('asyncCalc');
// asyncCalc: 0.962ms
// Result: 49999995000000
Can someone explain this to me please?