0

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

Ranieri Mazili
  • 723
  • 6
  • 21
  • Async still blocks unless the execution of the function is by another thread (like xhr requests, etc) – evolutionxbox Jan 13 '20 at 11:28
  • The Function is Async that is why it is running an independent Thread. If you will use await the other will not run until it will finish the previous response. – Salil Sharma Jan 13 '20 at 11:31
  • @SalilSharma did you ran the code? I'm not using await and the code is still being blocked by the async function. – Ranieri Mazili Jan 13 '20 at 11:56
  • @SalilSharma — It is **not** running on an independant thread. – Quentin Jan 13 '20 at 17:05
  • Two things (1) your `sleep()` function is blocking, (2) code in a `new Promise()` constructor runs synchronously. The observed behaviour should be 100% expected. – Roamer-1888 Jan 14 '20 at 01:40

0 Answers0