Skip to content

Instantly share code, notes, and snippets.

@ehpc
Last active February 5, 2020 07:37
Show Gist options
  • Save ehpc/99663220408c1a4d318fc0ba6a5a8ba8 to your computer and use it in GitHub Desktop.
Save ehpc/99663220408c1a4d318fc0ba6a5a8ba8 to your computer and use it in GitHub Desktop.
async keyword doesn't make your function asynchronous
function heavyFunc() {
const limit = Math.pow(10, 8);
let res = 0;
for (let i = 1; i < limit; i++) {
res += Math.atan2(i, i) * Math.random();
}
return res;
}
async function heavyFuncWithAsync() {
const limit = Math.pow(10, 8);
let res = 0;
for (let i = 1; i < limit; i++) {
res += Math.atan2(i, i) * Math.random();
}
return res;
}
console.log('Starting heavyFunc. Current timestamp:', performance.now());
const res = heavyFunc();
console.log('Result of heavyFunc:', res);
console.log('Current timestamp:', performance.now());
console.log('Starting heavyFunc with async. Current timestamp:', performance.now());
const asyncRes = heavyFuncWithAsync();
console.log('Result of heavyFunc with async:', asyncRes);
console.log('Current timestamp:', performance.now());
/*
10:36:18.290 async:21 Starting heavyFunc. Current timestamp: 411333.0799999967
10:36:23.573 async:23 Result of heavyFunc: 39269864.55848782
10:36:23.574 async:24 Current timestamp: 416617.12499999703
10:36:23.574 async:26 Starting heavyFunc with async. Current timestamp: 416617.1800000011
10:36:28.570 async:28 Result of heavyFunc with async: Promise {<resolved>: 39267627.19725549}
10:36:28.571 async:29 Current timestamp: 421614.19499999465
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment