我正在使用Bookshelf.js(一个基于Promise的ORM模块)来执行几个数据库查找。给定用户提供的密钥,我需要确定密钥是否与两个表中的一个中的记录匹配。如果我在第一个表中找到它,我需要返回该记录。但是,如果我在第一个表中找不到它,我需要查看第二个表。基本上,我需要有条件地执行then
块。我如何使用承诺实现这一目标?这是我现在拥有的,非常混乱的,事实上,如果我在第一个resolve
查询中调用School
,我会有点不清楚会发生什么 - 第二个{{1阻止执行吗?
then
有没有更简洁的方法来写这个?
答案 0 :(得分:2)
您可以将整个else
逻辑保留在then
块内:
exports.findTargetRecord = function(code){
return new Promise(function(resolve, reject){
Schools
.query({ where: { code: code }})
.fetchOne()
.then(school => {
if(school) return resolve(school);
return Organizations
.query({ where: { code: code }})
.fetchOne()
.then(org => {
if(org) return resolve(org);
resolve(null);
})
})
.catch(err => reject(err));
});
};
此外,您的代码可以重写(较短版本),如下所示:
exports.findTargetRecord = function(code){
return Schools
.query({ where: { code: code }})
.fetchOne()
.then(school => {
if(school) return school;
return Organizations
.query({ where: { code: code }})
.fetchOne();
})
.catch(err => reject(err));
答案 1 :(得分:2)
将promises用作代理和常规if
:
exports.findTargetRecord = function(code){
const school = Schools.query({ where: { code: code }}).fetchOne();
school = school.then(school =>
school || Organizations.query({ where: { code: code }}).fetchOne())
return school;
}
或者蓝鸟支持的协程(蓝鸟与书架一起发货):
exports.findTargetRecord = Promise.coroutine(function*(code) {
var school = yield Schools.query({ where: { code: code }}).fetchOne();
if(school) return school;
return Organizations.query({ where: { code: code }}).fetchOne();
});