Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to mark function as async

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); } 
like image 382
Maksim Nesterenko Avatar asked May 22 '17 07:05

Maksim Nesterenko


People also ask

When should a function be async?

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.

Should I make all functions async?

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.

Should I use then or async?

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.

Why we use async instead of promises?

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.


1 Answers

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.

like image 121
Stephen Cleary Avatar answered Oct 22 '22 15:10

Stephen Cleary