Be careful inside try-catch blocks in Javascript async functions. If you don't use await
, an error that's thrown might not stop the execution of subsequent code. Consider this:
const evilFunction = async () => {throw new Error("I'm evil");};
const goodCode = async () => {
try {
await evilFunction();
console.log("Everything went well!"); // narrator: no, it didn't.
} catch (e) {}
};
const badCode = async () => {
try {
evilFunction();
console.log("Everything went well!"); // again, it didn't, but this time it's worse: the success message was actually logged.
} catch (e) {}
};
const goodCode = async () => {
try {
await evilFunction();
console.log("Everything went well!"); // narrator: no, it didn't.
} catch (e) {}
};
const badCode = async () => {
try {
evilFunction();
console.log("Everything went well!"); // again, it didn't, but this time it's worse: the success message was actually logged.
} catch (e) {}
};
The problem in the badCode
example is that since we're not waiting for the call to evilFunction
to return, the rest of the code continues executing.
Final thoughts
I love it when programming languages keep you on your toes with hard to debug details like this. /sarcasm