Are there any implications of using Promise.prototype.catch
inside of async functions where await
is used?
For example:
async funciton sendMessage(topic, bodyObj) {
// implementation is not important
}
async function removeFromInventory(item, amount) {
const storeData = await getSoreData(item)
const removeResult = await inventory.removeFromStore(storeData.id, item.id, amount)
sendMessage(
Message.REMOVE_INVENTORY_SUCCESS, removeResult
).catch(log.error) // <== here, is it has downside and it is better to use try/catch?
return removeResult
}
I do not want to await
for sendMessage
to complete and I use .catch
to handle rejections, in other words avoiding unhandled rejections.
Are there any implications of using Promise.prototype.catch inside of async functions where await is used?
The way you're using it, the main implication is that you're "eating" the error. You log the error and then continue on as if there was no error. If that's the design intention, it will work just fine.
As for the general topic, you are allowed to mix async/await
with .then()
and .catch()
. It will work - there's no language prohibition against it.
That said, it is not generally recommended to mix them as it can create more confusing code where it's not entirely clear if error handling and/or error propagation is being implemented consistently and correctly because you're mixing two different models of error handling.
The one and only time I tend to mix async/await
with .catch()
is when I want to log and "eat" an error while letting everything else continue as if there was no error.
For example, that often happens when deleting a temporary file inside a function that is otherwise using async/await
:
fs.promises.unlink(tempFile).catch(err => console.log(err));
I do it this way just because it's more compact that surround it with try/catch
and I'm "eating" the error because there's nothing useful to be done if this fails and the main operation has already completed successfully. I also may not put an await
because I don't actually need to main operation to wait for this cleanup to complete before it communicates back its completion.
For comparison, the other way to do this would be:
try {
await fs.promises.unlink(tempFile);
} catch(e) {
console.log(e);
}
So, if that is your intention with the sendMessage(...).catch()
, then this is perfectly OK. This will log the error and otherwise "eat" the error so processing will continue as if there was no error.
If, on the other hand, you want that error to propagate back to the caller, then this is not at all what you want because that won't happen. This code handles the error and hides it from propagation back to the caller.