我有以下代码:
var myFunc = function(id, obj, backupObj) {
return update(obj) // this returns a promise
.fail(function(err){
// if update is rejected
restore(id, backupObj); // i wish to run this
// and return the error that 'update(obj)' threw and propagate it
return Q.reject(err); // should it be thrown like this???
});
}
这是处理update()
失败并返回错误的正确方法吗?所以当从任何地方调用myFunc()
时,它可以传播并最终处理?例如,在链中执行:
var foo = function(id, obj) {
var backupObj = {};
return checkIfValidObj(obj)
.then(function(_backupObj) {
backupObj = _backupObj;
return doSomethingElse(id, obj);
})
.then(function() {
// here!
return myFunc(id, obj, backupObj);
});
}
然后,作为foo
调用者,我想做一些错误处理,并能够捕获update(obj).fail()
可能返回的错误:
foo()
.then(function() { /* everything worked as expected, so we are happy */ })
.catch(function(err){
// I want this to be executed also if 'update(obj)' inside 'myFunc' was rejected!
});