I recently read a book about async and await patterns, there's chapter about deferred await or early init. The book says:
This allows a structure that starts async processing early but only stops for it when the result is needed.
const wait = (ms) => new Promise(res => setTimeout(res, ms));
const fn = async () => {
console.log("starting");
await wait(100); // I suppose await should pause the execution
console.log("end");
}
(async () => {
const fnPromise = fn();
console.log("after"); // However after is printed brfore end
await fnPromise;
})();
And if I change the code a bit
(async () => {
await fn(); // looks like the inner await only takes effect when I await an async function
console.log("after"); // after is printed after end
})();
I mean what's the difference between await
an async function and directly calling it. Is there any best pratice about when to await
or when not to await
an async function. Does await
truly block the execution, especially combined with timers.
Thanks to @asynts's snippet, I'll post it here
let samples = 100 * 1000 * 1000;
let chunk = 100000;
async function run() {
let sum = 0.0;
for(let i=0; i<samples; i++) {
sum += Math.random();
if (i % chunk === 0) {
console.log("finished chunk")
// wait for the next tick
await new Promise(res => setTimeout(res, 0));
// If await truly blocks the execution, rest of the code are all waiting?
// If await doesn't block the execution, what's the point to await here
}
}
let mean = sum / samples;
console.log("finished computation", mean);
}
setTimeout(run, 0);