gpt4 book ai didi

javascript - 异步 Node js "For"循环与数据库查询

转载 作者:太空宇宙 更新时间:2023-11-04 02:55:04 25 4
gpt4 key购买 nike

这里是“for”循环,用于为数组中的每个“id”运行查询(SQLite3 数据库)。

qry = "SELECT patients.*, patient_visits.visit_id,patient_visits.patient_id, patient_visits.visitdate, patient_visits.visittime FROM patients LEFT JOIN patient_visits ON patients.id = patient_visits.patient_id "+where+" GROUP BY patients.id ORDER BY patients.id  DESC LIMIT "+limit+" OFFSET "+offset;
db.all(qry, (err, results) => {
if(err){
response.error = err;
res.send(response);
}else{
response.patients = patients;
for (var i = 0; i < patients.length; i++) {
response.patients[i].check = "false";
var patient = response.patients[i];
db.each("SELECT visit_id FROM patient_visits where patient_id='"+patient.id+"' AND visitdate >='"+moment().format('YYYY-MM-DD')+"'", function(err, row) {
if (row) {
response.patients[i].check = "true";
}
});
}
}
res.send(response);
});

问题在于 for 循环在查询完成之前继续进行。有没有办法检查查询是否完成?

最佳答案

请导入异步模块。

qry = "SELECT patients.*, patient_visits.visit_id,patient_visits.patient_id, patient_visits.visitdate, patient_visits.visittime FROM patients LEFT JOIN patient_visits ON patients.id = patient_visits.patient_id " + where + " GROUP BY patients.id ORDER BY patients.id  DESC LIMIT " + limit + " OFFSET " + offset;
db.all(qry, (err, results) => {
if (err) {
response.error = err;
res.send(response);
} else {
response.patients = patients;

async.forEachOf(patients, function (patient, key, callback) {
db.each("SELECT visit_id FROM patient_visits where patient_id='" + patients[key] + "' AND visitdate >='" + moment().format('YYYY-MM-DD') + "'", function (err, row) {
if (row) {
response.patients[i].check = "true";
}else{
callback();
}
});
}, function (error) {
if (error) {
console.log(error)
} else {
res.send(response);
}
})

}
});

关于javascript - 异步 Node js "For"循环与数据库查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53984072/

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