Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the benefit of prepending async to a function that returns a promise?

What is the benefit of prepending async here?

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

   });
}
like image 823
Mark Adel Avatar asked Dec 19 '17 05:12

Mark Adel


People also ask

What happens if an async function returns a promise?

Async functions always return a promise. If the return value of an async function is not explicitly a promise, it will be implicitly wrapped in a promise. Note: Even though the return value of an async function behaves as if it's wrapped in a Promise.resolve , they are not equivalent.

Why does async function return promise?

The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically. So, async ensures that the function returns a promise, and wraps non-promises in it.

How does async and promise work?

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.

What is the purpose of async await keywords?

The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.


2 Answers

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.

like image 112
Bergi Avatar answered Oct 23 '22 23:10

Bergi


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.

like image 27
Vipin Kumar Avatar answered Oct 23 '22 21:10

Vipin Kumar