I'm trying to understand async/await and read some articles about it, but I'm still having difficulties to understand some scenarios.
Here I have a code that blocks the processing (note I'm not using await to wait for the response):
async function myAsyncFunction() {
console.log("myAsyncFunction started");
return new Promise(resolve => {
sleep(5000);
console.log("myAsyncFunction finished");
resolve("myAsyncFunction value");
});
}
function myNormalFunction() {
console.log("myNormalFunction started");
sleep(2000);
console.log("myNormalFunction finished")
return "myNormalFunction valiue";
}
//Just a function to real block the thread
//Relax, I'll not use it in production
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
async function main() {
const ar = myAsyncFunction();
const sr = myNormalFunction();
}
main();
The output of this code will be:
myAsyncFunction started
myAsyncFunction finished
myNormalFunction started
myNormalFunction finished
...and I was expecting
myAsyncFunction started
myNormalFunction started
myNormalFunction finished
myAsyncFunction finished
If the purpose of an async function is not block the caller returning a promise, why on this example it's not working? Is there a way to make it work?
Thanks