javascript - 带有数据库查询的异步节点js“For”循环
问题描述
这是为数组中的每个“id”运行查询(SQLite3 数据库)的“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;
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);
}
})
}
});
推荐阅读
- python - 如何让用户在不使用 Django 表单的情况下手动在 Django 中保存或编辑他的个人资料信息
- mysql - 如何在mysql中捕获1行(0.01秒)
- postgresql - postgresql pg_trgm.word_similarity_threshold 递减
- typescript - Protractor 交互式调试会话 (elementExplorer) - 如何导入 .ts 或 .js 文件?
- python-3.x - 名称错误:未定义名称“日期时间”
- java - 如何让 Vaadin 10 组件从点击事件中一一变化?
- asp.net-mvc - 如何将联接数据传递给 MVC 中的视图
- vba - VBA 无效的限定符错误
- ms-access-2003 - 根据多列中的最小值选择多列(毫秒访问)
- r - 建立给定标量和json表格数据的数据框?