1

Must all functions which return a Promise be defined as async?

Until now, I was only defining as async the functions which take use of await... But I have seen people that also declare this function as async:

const getPeople = () => {
   return db.getPeople(); // A Promise
}

Like this:

const getPeople = async () => {
   return db.getPeople();
}

Why?

Raul
  • 2,673
  • 1
  • 15
  • 52
  • 2
    To answer the title: no. To answer the last question - because it marks the function as returning a promise. Easier to distinguish by just seeing the signature. It's a coding style, not much else to it. – VLAZ Feb 09 '21 at 12:48
  • 2
    If all it does is return a promise, I would say no. – evolutionxbox Feb 09 '21 at 12:50
  • 1
    @VLAZ when it comes to functions that return a promise like `getPeople`, is there any performance difference between returning the promise vs `await`ing it like you said, and returning the resolved value? – TKoL Feb 09 '21 at 12:53
  • 1
    Also, any performance difference between marking it as `async` vs not marking it as `async`? – TKoL Feb 09 '21 at 12:54
  • @TKoL I've removed the comment since the difference is a bit of a corner case and it's not very relevant as this is just an example. Still, if you're interested [this is a good article](https://jakearchibald.com/2017/await-vs-return-vs-return-await/) explaining it as is [Difference between `return await promise` and `return promise`](https://stackoverflow.com/q/38708550). There shouldn't be a performance difference. But you *might* get slightly incorrect behaviour in some cases. – VLAZ Feb 09 '21 at 12:56
  • 1
    oh, i see. That difference is obvious enough imo, would be expected for anybody who knows what awaiting a promise vs returning a promise does. – TKoL Feb 09 '21 at 16:31

0 Answers0