What is the benefit of prepending async here?
async function asyncFunc () {
return new Promise (function (resolve, reject) {
});
}
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.
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.
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.
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.
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 function
s.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With