Let’s say there’s an async function that has an implementation bug, for example:
function resolveAfter2Seconds() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(undefined_variable);
}, 2000);
});
}
How can I call this function and handle the ReferenceError
it will throw?
I’ve tried using a .catch
block as follows:
resolveAfter2Seconds().then(result => console.log(result)).catch(error => console.log(error));
And also a wrapper function like so:
async function safeAsyncCall() {
try {
return await resolveAfter2Seconds()
} catch {
console.log("Something went wrong")
}
}
safeAsyncCall().then(result => console.log(result))
Neither of which work (the code still crashes with a ReferenceError
).
How can I safely call this function?