'Should I always use await in a chain of async functions return in Javascript?
Consider 2 ways of writing code:
The 1st ways: return instantly without await in async function.
function f4() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(2);
}, 3000);
}).catch((e) => console.log(e));
}
function f3() {
return f4();
}
function f2() {
return f3();
}
function f1() {
return f2();
}
async function main() {
await f1();
}
(async () => await main())();
and
the 2nd way: use await in every async function.
function f4() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(2);
}, 3000);
}).catch((e) => console.log(e));
}
async function f3() {
return await f4();
}
async function f2() {
return await f3();
}
async function f1() {
return await f2();
}
async function main() {
await f1();
}
(async () => await main())();
I think the 2nd way needs more time to execute code. But I'm not sure about that.
We see, when we use the 1st way, just only 1 Promise will go to callback. But with the 2nd way, we will have more than 1 Promise go into callback.
Which way gives better performance? Thank you very much.
Solution 1:[1]
Awaiting a Promise and immediately returning it inside an async function has no real benefit.
The value will be wrapped in a Promise again because async functions always return a Promise. You might as well return the initial Promise returned by f4 all the way to main instead of unwrapping and wrapping it along the way.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
