skip to Main Content

I have this function on a class. It is returning a promise.

static blabla(): Promise <number> {
  return new Promise < number > ((resolve) => {
    resolve(999);
  });
}

This function works fine but I would like to confirm if I need (for good practise) to use async like

static async blabla(): Promise <number>

3

Answers


  1. In your specific use-case, using async is not required.
    But when it comes to the futuristic aspect having async in method signature clearly indicates that this is asynchronous function and does need to be await accordingly who plans to consume the method given that in future there is another business logic depending upon result of the this method.

    In this way as a good practice and for consistency and readability, especially if you anticipate the need to handle more complex asynchronous operations in the future it is better to use async for code quality.

    Login or Signup to reply.
  2. You don’t need to use async if your function already returns a Promise. The async keyword is helpful if you want to use await inside the function, making it easier to work with other promises. Since your function directly returns a Promise, it works fine without async.

    You don’t need to use the async keyword in JavaScript if your function already returns a Promise.

    static blabla(): Promise<number> {
      return new Promise<number>((resolve) => {
        resolve(999);
      });
    }
    

    Here is an example of how you could utilize asynchronous programming in a more intricate function:

    static async example(): Promise<number> {
      const result = await someAsyncFunction(); // Using await for another promise
      return result + 999; // Now it makes sense to use async
    }
    
    Login or Signup to reply.
  3. "async" keyword is used to make a function return a "Promise" implicitly and to allow the use of the "await" keyword inside the function. In your case, since the function already returns a "Promise" explicitly and does not use the "await", using "async" is not necessary.

    IF you insist and want to add "async" you could and should refactor the function to be:
    static async blabla(): Promise<number> { return 999; }
    The function now returns implicitly "Promise" and the async keyword makes this clear.

    Both versions are functionality equivalent.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search