我曾经使用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
传播过程中出现错误 - 它应该处理它,我接近我所期待的吗?我怎么能最终实现呢?
答案 0 :(得分:3)
我只看到两个问题。
如果您希望使用值显式返回被拒绝的承诺,则应使用Q.reject
执行此操作。
在promise上调用.done()
意味着承诺在那里结束。它无法进一步链接。
所以,你的代码看起来像这样
exports.update = function (id, template) {
if (!_isValid(template)) {
return Q.reject(new Error('Invalid data', Error.INVALID_DATA));
}
return _update(id, template);
};
现在,update
函数只返回一个承诺。由呼叫者将成功或失败处理程序附加到其上。