cha*_*nie 5 javascript node.js promise q
我有以下代码:
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???
});
}
Run Code Online (Sandbox Code Playgroud)
这是处理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);
});
}
Run Code Online (Sandbox Code Playgroud)
然后,作为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!
});
Run Code Online (Sandbox Code Playgroud)