重构:从值或现有承诺返回承诺 [英] Refactoring: returning a promise from a value or an existing promise
问题描述
我曾经使用完成了一些
但我现在正在重构我的代码以使用 node.js
的实现回调 Promises
- 使用 Q
模块。我有以下 update()
函数,其中内部 _update()
函数已经返回承诺
:
I used to have some node.js
implementation done using callbacks
but I am now refactoring my code to use Promises
instead - using Q
module. I have the following update()
function where the inner _update()
function already returns a 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()
已经返回承诺
,我想用这种方式改变它就足够了(不会?):
Because _update()
already returns a promise
, I guess changing it this way would be enough (wouldn't be?):
return _update(id, template)
.done();
如果条件
在 if子句中
等于 true
?我怎么能重构
And... what about if the condition
inside the if-clause
equals true
? How could I refactor
返回回调(新错误('无效数据',BaboonError.INVALID_DATA));
抛出错误
以避免将回调
传递给 update()
并处理该错误(或者错误可能会返回 _update()
)?
to throw an error
to avoid passing the callback
into update()
and handling that error (or what ever error could ever be returning _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 */});
我的代码中的其他地方:
somewhere else in my code:
- 如果
承诺
传播期间出错 - 它应该处理它, - 或者,如果有这不是一个错误 - 它应该做一些其他的事情
- if there is an error during the
promise
propagation - it should handle it, - or, if there wasn't an error - it should do some other things
我接近我所期待的吗?我怎么能最终实现呢?
Am I close to what I am expecting? How could I finally achieve it?
推荐答案
我只看到两个问题。
-
如果您想显式返回带有值的被拒绝的承诺,您应该使用
Q.reject
。
致电 .done()$承诺的c $ c>
意味着承诺在那里结束。它不能被进一步链接。
Calling .done()
on promise means that the promise ends there. It cannot be chained further.
所以,你的代码看起来像这样
So, your code would look like this
exports.update = function (id, template) {
if (!_isValid(template)) {
return Q.reject(new Error('Invalid data', Error.INVALID_DATA));
}
return _update(id, template);
};
现在,更新
函数只返回一个永远承诺。由呼叫者连接成功或失败处理程序。
Now, the update
function just returns a promise always. Its up to the callers to attach the success or failure handlers to it.
这篇关于重构:从值或现有承诺返回承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!