7

What is the benefit of prepending async here?

async function asyncFunc () {
   return new Promise (function (resolve, reject) {

   });
}
Mark Adel
  • 223
  • 1
  • 10
  • Does Promise/asyncFunc contain a request that is asynchronous, otherwise its really not needed to use async keyword for your function – Shubham Khatri Dec 19 '17 at 05:29
  • 4
    Absolutely none. – Bergi Dec 19 '17 at 05:30
  • @Bergi - I like that it's a quick visualization that it returns a promise. It's nice if you have all of your functions collapsed in your IDE because you want to scan the available "public" methods. – VtoCorleone Dec 19 '17 at 05:39
  • @VtoCorleone I think you should be able to infer that from the function/method name and your knowledge of what makes sense in your application. Otherwise you will want to use type signatures (e.g. Flow or TypeScript) anyway. – Bergi Dec 19 '17 at 05:42
  • @Bergi - I guess it's a preference then. I know node.js has many async appended method names but with the "new" async syntax, I'd like to think that most methods are not synchronous unless stated that they are (in my own code). After explaining this, I'm probably going against the grain but I'm not a fan of using `async` in a method name any more. – VtoCorleone Dec 19 '17 at 05:51
  • 2
    @VtoCorleone I didn't mean a prefix/suffix in the method name, but just domain knowledge. For example `Math.max` returns a number, `ajax` and `readConfig` return a promise (for, uh, something). Yes, the `async` keyword *is* a quick visual reminder that the function returns a promise, but for the purpose of having an API overview I would prefer complete type signatures. – Bergi Dec 19 '17 at 05:56

2 Answers2

8

The only benefit of async is as a visual marker that the function will (always) return a promise, and you don't even have to scan the function body for the return statement. It might be useful for consistency if you have a row of async functions.

Apart from that: there's absolutely zero benefit from it. It's as good as wrapping the return value in an additional Promise.resolve() call. If your function body only consists of a return statement with a promise (either a new Promise or another function call), I recommend not to use async.

In general, if your function body does not contain an await expression, you probably don't need the async keyword either. The exception from the rule is when you want to make sure that the function always returns a promise, even if there's an exception raised in the code which should lead to a promise rejection.

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

I don't think there is any benefit of using async here unless your are using await inside your promise function.

async function asyncFunc () {
   // no await here
}

async/await are used in conjunction and there is no point of using one without other.

Vipin Kumar
  • 6,441
  • 1
  • 19
  • 25