2

I’m wondering in which code it makes more sense, is there any point in returning the promise like this if the promise does not contain a value:

async function action () {
  // let's say there are many such lines with await before returning
  await asyncFunction()

  // will return Promise that does not contain any value!
  return anotherAsyncFunction()
}

// action().then(myAnotherAction)

Or it would be wiser to do so:

async function action () {
  await asyncFunction()


  await anotherAsyncFunction()
}

// const result = await action()

The first option is to use only when returning some value?

Otherwise, it is easier to use the second option, because it is easier to add another action with "await" to the end of the function?

async function action () {
  await asyncFunction()

  await anotherAsyncFunction()
  // easy to add another function, no need to touch "return"
  await andAnotherAsyncFunction()
}
alexmac
  • 19,087
  • 7
  • 58
  • 69

1 Answers1

2

If you plan for your function not to return any value (Promise<void>), I would recommend not to use a return statement. You would only use return anotherAsyncFunction() if you wanted to always return the same result as anotherAsyncFunction, regardless of what it was or whether it would change in the future.

Notice it's the same for synchronous functions, if you leave await out of the picture you have the same decision to make: return something vs just something. That the "something" might contain an await doesn't really matter, even if you omit the await when you choose to add the return.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375