我目前有一个带条件的函数,每个条件都需要对我的数据库进行新的调用。为了避免异步问题,我目前正在将后续条件放在查询的响应中。我的代码目前看起来像这样:
checkNumberQuery = "SELECT Code FROM checkouts WHERE UserID =" + userID + " AND CheckOutEndDate >= '" + currentDateTime +"'";
conn.query(checkNumberQuery, function(err, response) {
if (err) {
logger.error({
"function": "checkNumberQuery",
"timestamp": Date.now(),
"error": err,
"reqBody": req.body
});
}
else {
if (response.length > 3){
result = "Unable to check-out. You already have three check outs";
continueCb(err, result);
}
else{
var newDateTime = moment().add(5, 'days').utc().format('YYYY-MM-DD HH:mm');
extendQuery = "UPDATE checkouts SET CheckOutEndDate = '"+ newDateTime +"' WHERE UserID =" + userID + " AND Code = " + userCode;
conn.query(extendQuery, function(err, response) {
if (err) {
logger.error({
"function": "extendQuery",
"timestamp": Date.now(),
"error": err,
"reqBody": req.body
});
}
else {
result = "Check-out period has been extended to " + newDateTime;
continueCb(err, result);
}
});
}
}
});
此代码位于异步瀑布内,这就是我调用continueCb(err, result)
的原因。来自async的什么函数会让我等到查询完成后转到下一个条件而不是嵌套它们?我已经阅读了文档,但似乎找不到合适的文档。理想情况下,我希望能够将每个查询放在一个单独的函数中,当函数返回true
时,我会调用并继续运行,表明查询已完成。