javascriptasynchronousasync-awaitecmascript-2017

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);
}

Solution

  • 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.