Would it make any difference if I have:
async function test () {
const foo = await bar()
return Promise.all([promise1, promise2])
}
instead of:
async function test () {
const foo = await bar()
const [result1, result2] = await Promise.all([promise1, promise2])
// Given that I don't care about result1, result2 in this `test` function
return [result1, result2]
}
I get the same result if I do either. E.g. I can do this for either case:
test().then(([result1, result2]) => { ... })
but I am more curious about the underlying mechanism how they both behave the same.
In other words, how does async function handle it if inside the function I return a promise instead of a value?
Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.
Short answer: no, an async function doesn't have to returns a Promise.
Promise resolve() method: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.
Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.
I think you're effectively calling synchronous-like functions with await
within the promise chain which, according to this answer:
You are perfectly free to call either synchronous functions within the promise chain (from within .then() handlers) or asynchronous functions that then return a new promise.
When you return something from a .then() handler, you can return either a value (which becomes the resolved value of the parent promise) or you can return another promise (which chains onto the previous promise) or you can throw which works like returning a rejected promise (the promise chain becomes rejected).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With