Javascript 如何使用承诺有条件地执行第二个任务?
我正在使用Bookshelf.js(一个基于Promise的ORM模块)来执行一些数据库查找。给定用户提供的键,我需要确定该键是否与两个表之一中的记录匹配。如果我在第一个表中找到它,我需要返回该记录。但是,如果我没有在第一个表中找到它,我需要查看第二个表。基本上,我需要有条件地执行Javascript 如何使用承诺有条件地执行第二个任务?,javascript,node.js,promise,bookshelf.js,Javascript,Node.js,Promise,Bookshelf.js,我正在使用Bookshelf.js(一个基于Promise的ORM模块)来执行一些数据库查找。给定用户提供的键,我需要确定该键是否与两个表之一中的记录匹配。如果我在第一个表中找到它,我需要返回该记录。但是,如果我没有在第一个表中找到它,我需要查看第二个表。基本上,我需要有条件地执行然后块。我如何使用承诺来实现这一点?这是我目前拥有的,非常混乱,事实上,我有点不清楚如果我在第一次查找中调用resolve,会发生什么——第二次然后块也会执行吗 exports.findTargetRecord = f
然后块。我如何使用承诺来实现这一点?这是我目前拥有的,非常混乱,事实上,我有点不清楚如果我在第一次查找中调用resolve
,会发生什么——第二次然后块也会执行吗
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 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));
您只需将整个else
逻辑保存在中,然后
块:
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));
使用承诺作为代理,并在以下情况下使用常规的:
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;
}
或者与bluebird支持的协同程序(bluebird附带书架):
使用承诺作为代理,并在以下情况下使用常规的:
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;
}
或者与bluebird支持的协同程序(bluebird附带书架):
谢谢,这更像是我要找的。它仍然不是超级干净或易于阅读,但它与我目前拥有的最为不同,这给了我一些选择。谢谢,这更像是我正在寻找的。它仍然不是超级干净或易于阅读,但它与我目前拥有的最为不同,这给了我一些选择。