JavaScript Await and operator precedence


Example

You have to keep the operator precedence in mind when using await keyword.

Imagine that we have an asynchronous function which calls another asynchronous function, getUnicorn() which returns a Promise that resolves to an instance of class Unicorn. Now we want to get the size of the unicorn using the getSize() method of that class.

Look at the following code:

async function myAsyncFunction() {
    await getUnicorn().getSize();
}

At first sight, it seems valid, but it's not. Due to operator precedence, it's equivalent to the following:

async function myAsyncFunction() {
    await (getUnicorn().getSize());
}

Here we attempt to call getSize() method of the Promise object, which isn't what we want.

Instead, we should use brackets to denote that we first want to wait for the unicorn, and then call getSize() method of the result:

async function asyncFunction() {
    (await getUnicorn()).getSize();
}

Of course. the previous version could be valid in some cases, for example, if the getUnicorn() function was synchronous, but the getSize() method was asynchronous.