Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  192] [ 4]  / answers: 1 / hits: 56966  / 11 Years ago, tue, january 21, 2014, 12:00:00

This is probably a silly question, but mid promise chain, how do you reject a promise from inside one of the then functions? For example:



someActionThatReturnsAPromise()
.then(function(resource) {
return modifyResource(resource)
})
.then(function(modifiedResource) {
if (!isValid(modifiedResource)) {
var validationError = getValidationError(modifiedResource);
// fail promise with validationError
}
})
.catch(function() {
// oh noes
});


There's no longer a reference to the original resolve/reject function or the PromiseResolver. Am I just supposed to add return Promise.reject(validationError); ?


More From » promise

 Answers
11

Am I just supposed to add return Promise.reject(validationError);?




Yes. However, it's that complicated only in jQuery, with a Promise/A+-compliant library you also could simply



throw validationError;


So your code would then look like



someActionThatReturnsAPromise()
.then(modifyResource)
.then(function(modifiedResource) {
if (!isValid(modifiedResource))
throw getValidationError(modifiedResource);
// else !
return modifiedResource;
})
.catch(function() {
// oh noes
});

[#73039] Sunday, January 19, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
milor

Total Points: 284
Total Questions: 93
Total Answers: 115

Location: Venezuela
Member since Thu, Jul 15, 2021
3 Years ago
milor questions
;