【发布时间】:2018-02-13 13:02:58
【问题描述】:
我有一个循环,每次迭代都会运行并将记录插入到 mysql 数据库中。问题是我认为异步正在搞砸对数据库的写入。如果我有一个 10 次迭代循环,则只有 8 个插入被记录(例如)。 我试图找到一种方法让循环等待更新发生,然后再继续循环的下一次迭代。代码如下:
var queryString1 = "insert into expense_summary "+
"(user_id, customer_id, expense_date, category, cost) values (?,?,?,?,?)"
connection.query(queryString1, [
detail[0].employee,
detail[0].customer,
detail[0].date,
detail[0].category,
detail[0].total], function(err, result) {
var summaryId = result.insertId;
console.log("This is the summary ID" + summaryId);
var data;
for (i = 0; i < detail.length; i++) {
var queryString = "insert into expense_detail "+
"(expense_summary_id, expense_date, line_id, item_name, description, cost_per, quantity, tax, user_id, customer_id, expense_category_id, ad_hoc, reimbursable) "+
"values (?,?,?,?,?,?,?,?,?,?,?,?,?)";
connection.query(queryString, [
summaryId,
detail[i].date,
detail[i].line,
detail[i].item,
detail[i].description,
detail[i].cost,
detail[i].quantity,
detail[i].tax,
detail[i].employee,
detail[i].customer,
detail[i].category,
detail[i].adHoc,
detail[i].reimbursable], function(err, result) {
if(err){
throw err;
} else{
console.log(result);
}
});
}
});
【问题讨论】:
-
从您的代码来看,似乎没有任何理由需要您在插入之间等待。但是,如果您仍然想这样做,请查看
async / await。 -
I'm trying to find a way to make the loop wait for the update to occur before going on to the next iteration of the loop.这是你做的,不是吗?
标签: javascript mysql node.js express