Do I have to wait for void async functions?

Viewed 3549

Imagine the following JavaScript:

async function f(x)
{
     var d = await NetworkRequest(x);
     d.ProcessResponse();
}

async function g()
{
    f(x);
    // Is network io completed now?

}

NetworkRequest is a genuinely async function, one that completes asynchronously. Question - by the time f() returns, can one be sure that ProcessResponse is done?

What if g is not declared as async - will that make a difference?

2 Answers

Async functions appear to be blocking, but they actually aren't. They return a promise that resolves to their return value, because they're still asynchronously executing. If you don't return anything, it'll just return a promise that doesn't resolve to anything. In g, you still have to await f(x).

Question - by the time f() returns, can one be sure that ProcessResponse is done?

Absolutely not.

f is declared async, it returns a promise and hands control back to g as soon as it goes to sleep while it awaits another promise.

That is before ProcessResponse is even called.

What if g is not declared as async - will that make a difference?

No


This can be demonstrated:

const obj = {
    ProcessResponse: () => console.log("Process Response")
};

function NetworkRequest() {
    return new Promise( res => setTimeout(() => res(obj), 1000) );
}



async function f(x)
{
     console.log("f, before await");
     var f = await NetworkRequest(x);
     console.log("f, after await");
     f.ProcessResponse();
     console.log("f, after Process Response");
}

async function g()
{
    console.log("g, before f");
    f(x);
    console.log("g, after f");
}

const x = "global";
g();

Related