0

I am dealing with some codebase and there was a discussion between me and a colleague whether to put async before the function name in this case. I'd say yes, because we have a Promise inside, but might be wrong here. Any advice?

return {
    **async ???** loadSmthForFilter: function (diseases) {
      return new Promise((resolve, reject) => {
        $.get('/api/bla', { diseases })
          .done(resolve)
          .fail(reject);
      });
    }

Ren
  • 944
  • 1
  • 13
  • 26

3 Answers3

2

You can, but you don't need to. It depends if you want to use the await operator (add the async keyword) or use the then function chaining (No need to add it).

If you choose to you have it in the wrong place

return {
  loadSmthForFilter: async function (diseases) {
   return new Promise((resolve, reject) => {
    $.get('/api/bla', { diseases })
      .done(resolve)
      .fail(reject);
   });
}

BTW you should just return $.get directly as that is a promise, no need to wrap it in another promise. See: What is the explicit promise construction antipattern and how do I avoid it?

Jamiec
  • 133,658
  • 13
  • 134
  • 193
0

You don't NEED to use async with this function. The function return a Promise but don't await one. But, I usually put async for a function that return a promise to await the output.

0

The async keyword can be very useful when needed, but it adds some extra overhead to the function call because it internally wraps a try/catch around the function body and it handles the return value differently and it creates a promise.

So, I use async only when needed and that's when I want to use await inside the function or very occasionally, when I want to take advantage of the automatic try/catch wrapping and I'm using asynchronous operations of some kind.

In your case, none of these situations seem to apply, so I'd remove the promise anti-pattern (manually wrapping a promise in another), return the promise that $.get() already returns and do this:

return {
    loadSmthForFilter: function (diseases) {
        return $.get('/api/bla', { diseases });
    }
};
jfriend00
  • 683,504
  • 96
  • 985
  • 979