ThomasReggi
ThomasReggi

Reputation: 59345

Is there any benefit to making a function async when it returns a promise?

When you have a function that doesn't await anything and returns a promise you can do this. This will return a promise that you can await.

function doSomethingAamzing ({id, animalType, accessToken}) {
  const url = `${url}/v1/${animalType}/${id}?access_token=${accessToken}`
  return request.get(url)
}

It's not necessary but we can do this.

async function doSomethingAamzing ({id, animalType, accessToken}) {
  const url = `${url}/v1/${animalType}/${id}?access_token=${accessToken}`
  return await request.get(url)
}

In the latter is easier to read as a developer that the function is async and will return a promise, which isn't very clear in the first function. The only reason I can think that it might be better practice to use the latter is if the code undergone some static code analysis that could benefit from the explicit async syntax.

Is there any benefit to making a function async when it returns a promise?

Upvotes: 2

Views: 203

Answers (1)

Bergi
Bergi

Reputation: 664206

The difference is not observable from outside (unless you get the function source via toString, not supported by current transpilers anyway), so there's no benefit here.

Making the function async might even slow it down a bit because the invocation involves more things, creating a new promise and resolving it.

The big advantage of async functions, apart from the increased maintainability you've already mentioned, is the error handling. Any exceptions thrown in the evaluation of the function body will be converted to a rejection of the returned promise, without needing to be explicit about this.

Notice you don't even need to use await here, you can return thenables directly1 from async functions:

async function doSomethingAamzing ({id, animalType, accessToken}) {
  const url = `${url}/v1/${animalType}/${id}?access_token=${accessToken}`
  return request.get(url)
}

1: unless you are returning inside a try block, where it does make a difference.

Upvotes: 2

Related Questions