I'm creating a resource loader function that returns a promise. The function does error logging:
function load(url) {
return request(..)
.catch(function(error) {
log(error);
throw error;
});
}
The function is used in various chains:
load(a).then(function(res1) {
load(b).then(function(res2) {
// res1 + res2
});
});
I'd like to be able to log the resource exception and stop the promise chain there. If I silence it the chain will lead to then
, if I throw again it turns out as an unhandled rejection.
Catching those globally via node's process
is not an options as other libraries on the platform might depend on it.
Can rejections be silenced and still prevent the fulfilment chain from continuing?
A standard ES6 promise only has three outcomes:
Once it is resolved or rejected, there is no ECMAScript standard way to tell it to not call any of its handlers.
There are some 3rd party promise libraries that support a .abort()
method or .cancel()
method. For example, Bluebird 3.x has a .cancel()
method that will stop the chain and not call either of the .then()
handlers for that promise.
The usual way of dealing with this using standard promises is to create either a known resolved or rejected state that indicates that the chain should not proceed and then you have to have the immediately linked .then()
handlers can check for that specific state. You could conceivably add .cancel()
functionality to standard promises also by adding a .cancel()
method and overriding .then()
and .catch()
to check the promise for a cancel state before calling the handlers.