I'm not sure if "fail-fast" is the best way to describe this methodology, but ever since I started to learn about programming I have always been taught to design functions like this:
function doSomething() {
... // do error-prone work here
if (!allGood) {
// Report error, cleanup and return immediately. Makes for cleaner,
// clearer code where error-handling is easily seen at the top
...
return;
}
// Success! Continue on with (potentially long and ugly) code that may distract from the error
}
As such, I'm trying to call a promisified function like so:
doSomethingAsync(param).catch(err => {
console.error(err);
}).then(() => {
// Continue on with the rest of the code
});
But this gives me behaviour akin to the finally
block of a classic try...catch...finally
statement, i.e. the then()
block will always be called, even after an error. Sometimes this is useful, but I rarely find myself needing such functionality (or try...catch
statements in general, for that matter).
So in the interest of failing as quickly and clearly as possible, is there a way that I can make the second example above work in the way that I expect (i.e. then()
is only executed if catch()
wasn't, yet a single catch()
will still catch all errors raised by doSomethingAsync()
)?