Reputation: 15012
Given the code samples below, is there any difference in behavior, and, if so, what are those differences?
return await promise
async function delay1Second() {
return (await delay(1000));
}
return promise
async function delay1Second() {
return delay(1000);
}
As I understand it, the first would have error-handling within the async function, and errors would bubble out of the async function's Promise. However, the second would require one less tick. Is this correct?
This snippet is just a common function to return a Promise for reference.
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
Upvotes: 251
Views: 103987
Reputation: 8043
return await
Contrary to some popular belief,
return await promise
is at least as fast asreturn promise
, due to how the spec and engines optimize the resolution of native promises. There's a proposal to makereturn promise
faster and you can also read about V8's optimization on async functions. Therefore, except for stylistic reasons,return await
is almost always preferable.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
The difference is using await
will resolve the promise before returning, but assuming you await the function then there's no difference.
Upvotes: 1
Reputation: 221
In our project, we decided to always use 'return await'. The argument is that "the risk of forgetting to add the 'await' when later on a try-catch block is put around the return expression justifies having the redundant 'await' now."
Upvotes: 11
Reputation: 442
return somePromise
will pass somePromise to the call site, and await
somePromise to settle at call site (if there is any). Therefore, if somePromise is rejected, it will not be handled by the local catch block, but the call site's catch block.async function foo () {
try {
return Promise.reject();
} catch (e) {
console.log('IN');
}
}
(async function main () {
try {
let a = await foo();
} catch (e) {
console.log('OUT');
}
})();
// 'OUT'
return await somePromise
will first await somePromise to settle locally. Therefore, the value or Exception will first be handled locally. => Local catch block will be executed if somePromise
is rejected.async function foo () {
try {
return await Promise.reject();
} catch (e) {
console.log('IN');
}
}
(async function main () {
try {
let a = await foo();
} catch (e) {
console.log('OUT');
}
})();
// 'IN'
return await Promise
awaits both locally and outside, return Promise
awaits only outsideasync function delay1Second() {
return delay(1000);
}
delay1Second()
;const result = await delay1Second();
delay1Second()
, function delay(1000)
returns a promise immediately with [[PromiseStatus]]: 'pending
. Let's call it delayPromise
.async function delay1Second() {
return delayPromise;
// delayPromise.[[PromiseStatus]]: 'pending'
// delayPromise.[[PromiseValue]]: undefined
}
Promise.resolve()
(Source). Because delay1Second
is an async function, we have:const result = await Promise.resolve(delayPromise);
// delayPromise.[[PromiseStatus]]: 'pending'
// delayPromise.[[PromiseValue]]: undefined
Promise.resolve(delayPromise)
returns delayPromise
without doing anything because the input is already a promise (see MDN Promise.resolve):const result = await delayPromise;
// delayPromise.[[PromiseStatus]]: 'pending'
// delayPromise.[[PromiseValue]]: undefined
await
waits until the delayPromise
is settled.delayPromise
is fulfilled with PromiseValue=1:const result = 1;
delayPromise
is rejected:// jump to catch block if there is any
async function delay1Second() {
return await delay(1000);
}
delay1Second()
;const result = await delay1Second();
delay1Second()
, function delay(1000)
returns a promise immediately with [[PromiseStatus]]: 'pending
. Let's call it delayPromise
.async function delay1Second() {
return await delayPromise;
// delayPromise.[[PromiseStatus]]: 'pending'
// delayPromise.[[PromiseValue]]: undefined
}
delayPromise
gets settled.delayPromise
is fulfilled with PromiseValue=1:async function delay1Second() {
return 1;
}
const result = await Promise.resolve(1); // let's call it "newPromise"
const result = await newPromise;
// newPromise.[[PromiseStatus]]: 'resolved'
// newPromise.[[PromiseValue]]: 1
const result = 1;
delayPromise
is rejected:// jump to catch block inside `delay1Second` if there is any
// let's say a value -1 is returned in the end
const result = await Promise.resolve(-1); // call it newPromise
const result = await newPromise;
// newPromise.[[PromiseStatus]]: 'resolved'
// newPromise.[[PromiseValue]]: -1
const result = -1;
Glossary:
Promise.[[PromiseStatus]]
changes from pending
to resolved
or rejected
Upvotes: 31
Reputation: 24775
Here is a typescript example that you can run and convince yourself that you need that "return await"
async function test() {
try {
return await throwErr(); // this is correct
// return throwErr(); // this will prevent inner catch to ever to be reached
}
catch (err) {
console.log("inner catch is reached")
return
}
}
const throwErr = async () => {
throw("Fake error")
}
void test().then(() => {
console.log("done")
}).catch(e => {
console.log("outer catch is reached")
});
Upvotes: 3
Reputation: 51
here i leave some code practical for you can undertand it the diferrence
let x = async function () {
return new Promise((res, rej) => {
setTimeout(async function () {
console.log("finished 1");
return await new Promise((resolve, reject) => { // delete the return and you will see the difference
setTimeout(function () {
resolve("woo2");
console.log("finished 2");
}, 5000);
});
res("woo1");
}, 3000);
});
};
(async function () {
var counter = 0;
const a = setInterval(function () { // counter for every second, this is just to see the precision and understand the code
if (counter == 7) {
clearInterval(a);
}
console.log(counter);
counter = counter + 1;
}, 1000);
console.time("time1");
console.log("hello i starting first of all");
await x();
console.log("more code...");
console.timeEnd("time1");
})();
the function "x" just is a function async than it have other fucn if will delete the return it print "more code..."
the variable x is just an asynchronous function that in turn has another asynchronous function, in the main of the code we invoke a wait to call the function of the variable x, when it completes it follows the sequence of the code, that would be normal for "async / await ", but inside the x function there is another asynchronous function, and this returns a promise or returns a" promise "it will stay inside the x function, forgetting the main code, that is, it will not print the" console.log ("more code .. "), on the other hand if we put" await "it will wait for every function that completes and finally follows the normal sequence of the main code.
below the "console.log (" finished 1 "delete the" return ", you will see the behavior.
Upvotes: -1
Reputation: 9326
As other answers mentioned, there is likely a slight performance benefit when letting the promise bubble up by returning it directly — simply because you don’t have to await the result first and then wrap it with another promise again. However, no one has talked about tail call optimization yet.
Tail call optimization, or “proper tail calls”, is a technique that the interpreter uses to optimize the call stack. Currently, not many runtimes support it yet — even though it’s technically part of the ES6 Standard — but it’s possible support might be added in the future, so you can prepare for that by writing good code in the present.
In a nutshell, TCO (or PTC) optimizes the call stack by not opening a new frame for a function that is directly returned by another function. Instead, it reuses the same frame.
async function delay1Second() {
return delay(1000);
}
Since delay()
is directly returned by delay1Second()
, runtimes supporting PTC will first open a frame for delay1Second()
(the outer function), but then instead of opening another frame for delay()
(the inner function), it will just reuse the same frame that was opened for the outer function. This optimizes the stack because it can prevent a stack overflow (hehe) with very large recursive functions, e.g., fibonacci(5e+25)
. Essentially it becomes a loop, which is much faster.
PTC is only enabled when the inner function is directly returned. It’s not used when the result of the function is altered before it is returned, for example, if you had return (delay(1000) || null)
, or return await delay(1000)
.
But like I said, most runtimes and browsers don’t support PTC yet, so it probably doesn’t make a huge difference now, but it couldn’t hurt to future-proof your code.
Read more in this question: Node.js: Are there optimizations for tail calls in async functions?
Upvotes: 35
Reputation: 5622
Most of the time, there is no observable difference between return
and return await
. Both versions of delay1Second
have the exact same observable behavior (but depending on the implementation, the return await
version might use slightly more memory because an intermediate Promise
object might be created).
However, as @PitaJ pointed out, there is one case where there is a difference: if the return
or return await
is nested in a try
-catch
block. Consider this example
async function rejectionWithReturnAwait () {
try {
return await Promise.reject(new Error())
} catch (e) {
return 'Saved!'
}
}
async function rejectionWithReturn () {
try {
return Promise.reject(new Error())
} catch (e) {
return 'Saved!'
}
}
In the first version, the async function awaits the rejected promise before returning its result, which causes the rejection to be turned into an exception and the catch
clause to be reached; the function will thus return a promise resolving to the string "Saved!".
The second version of the function, however, does return the rejected promise directly without awaiting it within the async function, which means that the catch
case is not called and the caller gets the rejection instead.
Upvotes: 333
Reputation: 55688
This is a hard question to answer, because it depends in practice on how your transpiler (probably babel
) actually renders async/await
. The things that are clear regardless:
Both implementations should behave the same, though the first implementation may have one less Promise
in the chain.
Especially if you drop the unnecessary await
, the second version would not require any extra code from the transpiler, while the first one does.
So from a code performance and debugging perspective, the second version is preferable, though only very slightly so, while the first version has a slight legibility benefit, in that it clearly indicates that it returns a promise.
Upvotes: 5