Await and operator precedence
suggest changeKeep operator precedence in mind when you use await.
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());
}
That calls getSize on the promise, not on the unicorn. A promise has no such method, so this throws a TypeError.
Parentheses wait for the unicorn first, then call getSize() on the result:
async function asyncFunction() {
(await getUnicorn()).getSize();
}
The unparenthesized call is valid only when getUnicorn() itself returns an object with a getSize() method, for example when getUnicorn() is synchronous and getSize() returns a promise.