naivePromiseAPI() {
if (foo) {
throw new Error('this will get swallowed!');
}
return somePromise();
}
Instead you want this:
cleverPromiseAPI() {
return Promise.resolve().then(function () {
if (foo) {
throw new Error('this won't get swallowed!');
}
return somePromise();
});
}
Because if the client of the API does something like this:
$('.my-button').on('click', function () {
cleverPromiseAPI().catch(console.log.bind(console));
});
Then the client might expect the error to get console.logged, but actually it won't in the naive case. That's because the error was thrown synchronously and thus bubbled up to the click handler, instead of being caught inside of the promise chain.