我的问题是基于联合循环嵌套查询父阵列结果- PG-承诺 。 我有一个类似的情况,但有多个查询相结合,让我的最终结果。 以下是我的代码,我试图执行我的要求。 但是,我没能得到第二个查询与主查询相结合的结果。 我是一个初学者,想知道实现的正确途径。
db.task(t => {
const a = studies => t.any ('SELECT facility_contacts.name, facility_contacts.email, facility_contacts.phone FROM facility_contacts WHERE nct_id = $1', studies.nct_id).then(facility_contacts => {
studies.facility_contacts = facility_contacts;
return studies
});
const b = studies => t.any ('SELECT eligibilities.criteria, eligibilities.gender FROM eligibilities WHERE nct_id = $1', studies.nct_id).then(eligibilities => {
studies.eligibilities = eligibilities;
return studies;
});
return t.map('SELECT studies.nct_id, studies.official_title, studies.phase, facilities.country FROM studies, facilities WHERE facilities.country LIKE \'%Ireland%\' LIMIT 10',[], a, b).then(t.batch);
}).then(studies => {
console.log(studies);
res.send(studies);
}).catch(error => {
console.log(error);
});
提前致谢。
这里有一个可能性:
db.task(t => {
const a = studies => t.any('SELECT facility_contacts.name, facility_contacts.email, facility_contacts.phone FROM facility_contacts WHERE nct_id = $1', studies.nct_id)
.then(facility_contacts => {
studies.facility_contacts = facility_contacts;
return studies
});
const b = studies => t.any('SELECT eligibilities.criteria, eligibilities.gender FROM eligibilities WHERE nct_id = $1', studies.nct_id)
.then(eligibilities => {
studies.eligibilities = eligibilities;
return studies;
});
const c = studies => t.batch([a(studies), b(studies)]);
return t.map('SELECT studies.nct_id, studies.official_title, studies.phase, facilities.country FROM studies, facilities WHERE facilities.country LIKE \'%Ireland%\' LIMIT 10', [], c)
.then(t.batch);
})
.then(studies => {
console.log(studies);
res.send(studies);
})
.catch(error => {
console.log(error);
});
可以有很多不同的方法,有些方法性能更好,像基于JSON。
您可以使用Promise.all让所有结果
db.task(t => {
const queries = [
t.any('SELECT facility_contacts.name, facility_contacts.email, facility_contacts.phone FROM facility_contacts WHERE nct_id = $1', studies.nct_id),
t.any('SELECT eligibilities.criteria, eligibilities.gender FROM eligibilities WHERE nct_id = $1', studies.nct_id),
t.map('SELECT studies.nct_id, studies.official_title, studies.phase, facilities.country FROM studies, facilities WHERE facilities.country LIKE \'%Ireland%\' LIMIT 10', [], a, b)
];
return Promise.all(queries);
}).then((ResultArrayOfQueries) => {
console.log(ResultArrayOfQueries);
// Combine as per your requirement
res.send(ResultArrayOfQueries);
}).catch(error => {
console.log(error);
});