如何在 node.js 中用 Q 承诺重写一系列条件语句? [英] How do I rewrite a series of conditional statements with Q promises in node.js?
问题描述
exports.create = function(req, res) {
var company_id = req.company_id;
var client = new Client(req.body);
Company.findOne({_id: company_id}, function(err, company) {
if(err) {
response = {
status: 'error',
error: err
}
return res.json(response);
} else if(!company) {
response = {
status: 'error',
error: 'Invalid company_id'
}
return res.json(response);
} else {
client.save(function(err) {
if(err) {
response = {
status: 'error',
error: err
}
} else {
response = {
status: 'ok',
client: client
}
}
return res.json(response);
});
}
});
}
这是我的代码(使用 Express
,如果重要的话).我正在尝试更多地了解 Promise,特别是 Q
.我觉得这是一种完美的逻辑,可以通过 promise 来实现,以避免这种毛茸茸的条件嵌套.但我不知道如何开始?
That's my code (using Express
, if it matters). I'm trying to learn more about promises, specifically with Q
. I feel that this is the perfect kind of logic that can be implemented with promises to avoid this hairy conditional nest. But I'm not sure how to start?
推荐答案
但我不知道如何开始?
But I'm not sure how to start?
首先移除回调并使用 Promise 方法.然后将错误处理放在专用的错误回调中,而不是使用该条件.此外,您可以将用于构建 response
对象的代码放在最后(删除重复),并且只将 err
传递/抛出给它.
Start by removing the callbacks and using the Promise methods instead. Then put the error handling in a dedicated error callback, instead of using that condition. Also, you can put the code for building that response
object in the very end (removing the duplication), and only pass/throw the err
down to it.
exports.create = function(req, res) {
var client = new Client(req.body);
Q.ninvoke(Company, "findOne", {_id: req.company_id}).then(function(company) {
if(!company)
throw 'Invalid company_id';
else
return company;
}).then(function(company) {
return Q.ninvoke(client, "save");
}).then(function(saveResult) {
return {
status: 'ok',
client: client
};
}, function(err) {
return {
status: 'error',
error: err
};
}).done(function(response) {
res.json(response);
});
};
这篇关于如何在 node.js 中用 Q 承诺重写一系列条件语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!