Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Return a promise inside async function

Tags:

javascript

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?

like image 893
BPm Avatar asked Jan 13 '17 15:01

BPm


People also ask

Does an async function return a promise?

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.

Do you need to manually return a promise in an async JavaScript function?

Short answer: no, an async function doesn't have to returns a Promise.

How do I return a promise from a function?

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.

Can we use promise and async await together?

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.


1 Answers

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).

like image 67
Scott Weaver Avatar answered Oct 25 '22 02:10

Scott Weaver