如何拒绝从内而外的承诺呢

这可能是一个愚蠢的问题,但中期承诺链,你如何拒绝一个承诺从内部的一个当时的功能?例如:

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
});

不再有原始的解决/拒绝函数或者誓言解决程序的引用。我是不是应该加上 return Promise.reject(validationError);

55338 次浏览

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
});