我的情景
我以前有一些node.js实现是使用callbacks完成的,但现在我正在重构代码以使用Promises --使用Q模块。我有以下update()函数,其中内部_update()函数已经返回了一个Promise
exports.update = function(id, template, callback) {
if (!_isValid(template)){
return callback(new Error('Invalid data', Error.INVALID_DATA));
}
_update(id, template) // this already returns a promise
.then(function() {
console.log('UPDATE was OK!');
callback();
}, function(err) {
console.log('UPDATE with ERRORs!');
callback(err);
});
};我的问题
我想实现以下几点:
exports.update = function(id, template) {
if (!_isValid(template)){
// how could I make it return a valid Promise Error?
return reject(new Error('Invalid data', Error.INVALID_DATA));
}
return _update(id, template) // return the promise
.done();
};因为_update()已经返回了一个promise,所以我想这样修改它就足够了(不是吗?):
return _update(id, template)
.done();还有..。如果condition中的if-clause等于true呢?我怎么能重构
return callback(new Error('Invalid data', BaboonError.INVALID_DATA));
抛出一个error以避免将callback传递给update()并处理该错误(或者任何错误都可能返回_update())?
同时,调用update()
myModule.update(someId, someTemplate)
.then(function() { /* if the promise returned ok, let's do something */ })
.catch(function(err) { /* wish to handle errors here if there was any */});在我代码中的其他地方:
promise传播过程中有错误-它应该处理它,我是否接近我所期望的?我怎么能最终做到这一点呢?
发布于 2015-11-27 02:27:43
https://stackoverflow.com/questions/33949435
复制相似问题