What is the difference between
return await foo()
and
const t = await foo();
return t
What is the difference between
return await foo()
and
const t = await foo();
return t
Basically, because return await
is redundant.
Look at it from a slightly higher level of how you actually use an async
function:
const myFunc = async () => {
return await doSomething();
};
await myFunc();
Any async
function is already going to return a Promise
, and must be dealt with as a Promise
(either directly as a Promise
, or by also await
-ing).
If you await
inside of the function, it's redundant because the function outside will also await
it in some way, so there is no reason to not just send the Promise
along and let the outer thing deal with it.
It's not syntactically wrong or incorrect and it generally won't cause issues. It's just entirely redundant which is why the linter triggers on it.
Using return await
does have some newly introduced benefits in v8 engine used by Node.js, Chrome and a few other browsers:
v8 introduced a --async-stack-traces
flag which as of V8 v7.3 is enabled by default (Node.js v12.0.0).
This flags provides an improved developer experience by enriching the Error stack property with async function calls stack trace.
async function foo() {
return bar();
}
async function bar() {
await Promise.resolve();
throw new Error('BEEP BEEP');
}
foo().catch(error => console.log(error.stack));
Error: BEEP BEEP
at bar (<anonymous>:7:9)
Note that by calling return bar();
foo()
function call does not appear at all in the error stack. Changing it to return await bar();
gives a much better error stack output:
async function foo() {
return await bar();
}
foo();
Error: BEEP BEEP
at bar (<anonymous>:7:9)
at async foo (<anonymous>:2:10)
This indeed does provide much better error stack tracing, hence it is HIGHLY encouraged to always await your promises.
Additionally, async/wait now outperforms hand written promises:
async/await
outperforms hand-written promise code now. The key takeaway here is that we significantly reduced the overhead of async functions — not just in V8, but across all JavaScript engines, by patching the spec. Source
Read more about these changes on the v8.dev blog: https://v8.dev/blog/fast-async#improved-developer-experience
Because you can just
async function() {
return foo();
}
The returned result of async function
always is Promise
, no matter you return the exact value or another Promise
object inside the function body
Update: The no-return-await
rule is now deprecated. The world is healing.
It seems many are debating the usefulness of return await
in the comments. Let me add a demonstration that shows how the stacktrace is affected.
In my opinion, skipping await
is a misguided attempt at some sense of "optimization", saving 6 characters and a microtask (EDIT: ShortFuse just showed that it is actually not saving but adding a microtask in current v8) at the cost of stacktraces, try-catches, refactorability and code consistency. The rule of the thumb is simple: if you have an async call, await it (unless you are doing fancy stuff like parallelism or async caching). I believe we should stick to the rule of thumb and always use return await
, and switch off that no-return-await
eslint rule.
little demo:
async function main() {
console.log("\nStatcktrace with await shows testStackWithAwait:");
await testStackWithAwait().catch(logStack);
console.log("\nStatcktrace without await hides testStackWithoutAwait:");
await testStackWithoutAwait().catch(logStack);
console.log("\nFinally happens before try block ends without await:");
await testFinallyWithoutAwait();
}
async function fnThatThrows() {
await delay(1);
throw new Error();
}
async function testStackWithoutAwait() {
return fnThatThrows(); // bad
}
async function testStackWithAwait() {
return await fnThatThrows(); // good
}
async function fnThatLogs() {
await delay(1);
console.log('inside');
}
async function testFinallyWithoutAwait() {
try {
return fnThatLogs(); // bad
} finally {
console.log('finally');
}
}
function logStack(e) {
console.log(e.stack);
}
function delay(timeout, value) {
return new Promise(resolve => {
setTimeout(() => {
resolve(value);
}, timeout);
});
}
main().catch(console.error);
On Chrome 103 on Windows I get the following logs:
Statcktrace with await shows testStackWithAwait:
Error
at fnThatThrows (https://stacksnippets.net/js:23:9)
at async testStackWithAwait (https://stacksnippets.net/js:31:10)
at async main (https://stacksnippets.net/js:14:3)
Statcktrace without await hides testStackWithoutAwait:
Error
at fnThatThrows (https://stacksnippets.net/js:23:9)
at async main (https://stacksnippets.net/js:16:3)
Finally happens before try block ends without await:
finally
inside
The significant difference between return asyncFunc and return await Promise.resolve() is by following the second approach you can catch an error if something wrong inside async function.
function afunction() {
return asyncFun();
}
// with await
async function afunction() {
try {
return await asyncFun();
} catch(err) {
handleError(err);
// return error result;
}
}
Oh I think is easy to understand, we put "await" when we wait for a specific value in order to continue a process, if the process is finished (look at the return), we don't need the await syntax anymore so.
return await foo(); //is redundant
return foo(); //is the correct way