Basically, function must be prefixed with async
keyword if await
used inside it. But if some function just returns Promise and doesn't awaiting for anything, should I mark the function as async
?
Seems like both correct or not?
// with async (returns Promise) async getActiveQueue() { return redisClient.zrangeAsync(activeQueue, 0, -1); } // difference? Both could be awaited isn't it? getActiveQueue() { return redisClient.zrangeAsync(activeQueue, 0, -1); }
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.
Changing functions to async is somewhat repetitive and unimaginative work. Throw an async keyword in the declaration, wrap the return value by Task<> and you're pretty much done. It's rather unsettling how easy the whole process is, and pretty soon a text-replacing script will automate most of the "porting" for me.
Async/await and then() are very similar. The difference is that in an async function, JavaScript will pause the function execution until the promise settles. With then() , the rest of the function will continue to execute but JavaScript won't execute the . then() callback until the promise settles.
Promise chains can become difficult to understand sometimes. Using Async/Await makes it easier to read and understand the flow of the program as compared to promise chains.
if some function just returns Promise and doesn't awaiting for anything, should I mark the function as async?
I would say you shouldn't. The purpose of async
/await
is to create (and resolve) the promise for you; if you already have a promise to return, then async
/await
won't give you any benefit for that function.
Both could be awaited isn't it?
await
works on promises, not functions. So, await
works fine on any promise, regardless of whether that promise is manually created or created behind the scenes by async
.
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