[英]Refactoring: returning a promise from a value or an existing promise
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. 我曾经使用callbacks
完成一些node.js
实现,但是现在我将代码重构为使用Promises
-使用Q
模块。 I have the following update()
function where the inner _update()
function already returns a Promise
: 我有以下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);
});
};
I would like to achieve something like the following : 我想实现以下目标 :
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();
};
Because _update()
already returns a promise
, I guess changing it this way would be enough (wouldn't be?): 因为_update()
已经返回一个promise
,所以我猜以这种方式进行更改就足够了(不是吗?):
return _update(id, template)
.done();
And... what about if the condition
inside the if-clause
equals true
? 而且...如果if-clause
的condition
等于true
怎么办? How could I refactor 我该如何重构
return callback(new Error('Invalid data', BaboonError.INVALID_DATA));
to throw an error
to avoid passing the callback
into update()
and handling that error (or what ever error could ever be returning _update()
)? 抛出一个error
以避免将callback
到update()
并处理该错误(或者曾经发生过什么错误可能返回_update()
)?
Also, calling 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 */});
somewhere else in my code: 我代码中的其他地方:
promise
propagation - it should handle it, 如果在promise
传播期间出现错误-应该处理该错误, Am I close to what I am expecting? 我是否接近预期? How could I finally achieve it? 我最终将如何实现?
I see only two problems. 我只看到两个问题。
If you want to explicitly return a rejected promise with a value, you should do that with Q.reject
. 如果要显式返回带有值的已拒绝承诺,则应使用Q.reject
。
Calling .done()
on promise means that the promise ends there. 在promise上调用.done()
意味着该promise在那里结束。 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. 现在, update
功能始终总是返回一个承诺。 Its up to the callers to attach the success or failure handlers to it. 由调用者决定是否将成功或失败处理程序附加到它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.