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
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 isasynchronous
function and does need to beawait
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.You don’t need to use
async
if your function already returns aPromise
. Theasync
keyword is helpful if you want to useawait
inside the function, making it easier to work with other promises. Since your function directly returns aPromise
, it works fine withoutasync
.You don’t need to use the async keyword in JavaScript if your function already returns a Promise.
Here is an example of how you could utilize asynchronous programming in a more intricate function:
"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.