gpt4 book ai didi

javascript - 如何使用 Promise 有条件地执行第二个任务?

转载 作者:太空宇宙 更新时间:2023-11-04 03:06:32 26 4
gpt4 key购买 nike

我正在使用 Bookshelf.js(一个基于 Promise 的 ORM 模块)来执行几个数据库查找。给定用户提供的 key ,我需要确定该 key 是否与两个表之一中的记录匹配。如果我在第一个表中找到它,我需要返回该记录。但是,如果我在第一个表中找不到它,我需要在第二个表中查找。基本上,我需要有条件地执行 then block 。我如何使用 promise 来实现这一点?这是我目前所拥有的,非常困惑,事实上,我有点不清楚如果我在第一个 School 查找中调用 resolve 会发生什么 - 第二个 then block 也会执行吗?

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));
});
};

有没有更简洁的方法来编写这个?

最佳答案

使用 Promise 作为代理和常规 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;
}

或者使用 bluebird 支持的协程(bluebird 附带书架):

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();
});

关于javascript - 如何使用 Promise 有条件地执行第二个任务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39374254/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com