【问题标题】:Force loop to wait for mysql insert before moving to next iteration强制循环在移动到下一次迭代之前等待 mysql 插入
【发布时间】: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


【解决方案1】:

如果你使用最新的 node.js > 8,你可以使用 async/await。

(async  () => {
        for (let i = 0; i < 10; i++) {
                console.log(i);
                await new Promise (resolve => setTimeout (resolve, 500))
        }
})();

将你的整个函数包装在 Promise 中,并用 timeout Promise 替换它。

或者您可以使用现代的 for ... of 循环,其中 await 将按预期工作:

async function query() {
  for (let d of detail) {
    const contents = await your_query_promise();
  }
}

【讨论】:

  • 您的第一个选项效果很好!非常感谢里德姆。我仍然需要进一步研究 async/await 之间的关系。再次感谢。
【解决方案2】:

它看起来是变量和范围的典型问题。 只需尝试更改以下 2 行:

for (let i=0; i<detail.length; i++){

    let 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 (?,?,?,?,?,?,?,?,?,?,?,?,?)";

声明变量可以避免在不同的迭代之间共享变量值

【讨论】:

    猜你喜欢
    • 2019-11-29
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 2015-05-12
    • 2020-04-08
    • 1970-01-01
    • 2012-10-13
    相关资源
    最近更新 更多