The two lines are not the same and any automated change between these two is most likely incorrect.
To simplify, the difference is between:
(await foo()).bar
await foo() .bar
:
Due to the operator precedence of await
the second code (await foo().bar
) will:
- Execute
foo()
- Read the property
bar
from it
await
that value
Which can be written as:
const functionResult = foo();
const result = await functionResult.bar;
While the first code uses the grouping operator ()
to change the order of operations to:
- Execute
foo()
await
that value
- Read the property
bar
from it
Which can be written as:
const functionResult = await foo();
const result = functionResult.bar;
This absolutely makes a difference if the function returns a promise:
function foo() {
return Promise.resolve({ bar: "hello world" });
}
async function main() {
console.log( await foo() .bar); // undefined - `foo()` returns a promise and there is no `bar` property
console.log((await foo()).bar); // "hello world" - since the promise resolves to { bar: "hello world" }
}
main();
It also makes a difference if foo()
is synchronous but the bar
property is a promise:
function foo() {
return { bar: Promise.resolve("hello world") };
}
async function main() {
console.log( await foo() .bar); // "hello world" since the promise resolves to that string
console.log((await foo()).bar); // Promise (check the browser console)
}
main();
The only time it does not make a difference is if there is no asynchronous code (which means the await
probably should not be there):
function foo() {
return { bar: "hello world" };
}
async function main() {
console.log( await foo() .bar); // "hello world"
console.log((await foo()).bar); // "hello world"
}
main();