When to mark an async function
Basically, a function must be prefixed with a keyword async
if await
used internally. But if some function just returns a Promise and waits for nothing, should I mark the function as async
?
Seems to be 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);
}
source to share
If some function just returns a Promise and waits for nothing, should the function be async?
I would say not worth it. Purpose async
/ await
is to create (and resolve) a promise for you; if you already have a promise to return, then async
/ await
won't give you any benefit for this feature.
Both can be expected, right?
await
works on promises, not functions. So it await
works great on any promises, whether it's manually created or created behind the scenes async
.
source to share
If a function called for an unknown reason throws an error, the async keyword will ensure that this function is returned as a rejected promise by your function.
the async keyword can also be used in functions that would like to return a promise (for example, for api consistency) from the return value only, without having to manually create the Promise object.
I would argue that the async keyword is not always expectable.
source to share
Keyword async
isn't just about providing the keyword await
in a function.
This ensures that your ALWAYS function returns a Promise even when an exception is thrown.
Here are some code snippets showing the difference:
async function f(x) {
if (!x)
throw new Error('failed')
return new Promise((resolve, reject) => {
resolve(x + 1);
});
}
f(false).then(
result => console.log('f result', result),
error => console.log('f async error', error)
);
If you miss the async keyword and your function throws an exception, it won't be converted to a promise and you need to catch it synchronously.
function g(x) {
if (!x)
throw new Error('failed');
return new Promise((resolve, reject) => {
resolve(x + 1);
});
}
try {
g(false).then(
result => console.log('g result', result),
)
}
catch (error) {
console.log('g sync error', error);
}
source to share