Reputation: 63189
The angular docs say you could chain promises, like this:
promiseB = promiseA.then(function(result) {
return result + 1;
});
Is it possible to reject promiseB
from within the function?
promiseB = promiseA.then(function(result) {
if (result > 0) {
return result + 1;
}
else {
// reject promiseB
}
});
P.S.: In this example I assume that promiseA
always resolves.
Upvotes: 3
Views: 129
Reputation: 449
You can, in fact, the .then() function takes two callback functions. One for success, and one for an error as specified in that same documentation. In the error handler callback you can use $q.reject() to reject the promise. However, with that said, you can also use it in the success callback too:
promiseB = promiseA.then(function(result) {
// success: do something and resolve promiseB
// with the old or a new result
if (!result || result !== "Whatever you're looking for" ) {
$q.reject("A Reason")
} // additional edit from me
return result;
}, function(reason) {
// error: handle the error if possible and
// resolve promiseB with newPromiseOrValue,
// otherwise forward the rejection to promiseB
if (canHandle(reason)) {
// handle the error and recover
return newPromiseOrValue;
}
return $q.reject(reason);
});
* Taken from Angular Documentation
Upvotes: 2
Reputation: 117370
promiseB = promiseA.then(function(result) {
if (result > 0) {
return result + 1;
}
else {
return $q.reject('whatever reason');
}
});
This works sine the return value of the success callback of the promiseA gets converted into another promise that is either resolved with the return value of the success callback or rejected if we explicitly reject it with $q.reject
or throw an exception.
Upvotes: 3