最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Express JS在for循环内的Express JS死锁

运维笔记admin22浏览0评论

Express JS在for循环内的Express JS死锁

Express JS在for循环内的Express JS死锁

我有一个具有node.jsexpressjs的应用程序,现在当我尝试将多个记录插入数据库时​​遇到了问题。

我有一个包含4条记录的数组,应用程序插入3,最后一个从sql返回死锁错误。

我认为这个问题可能是因为for循环内的promise。

接下来您将获得简历的代码:

 processOrder: (req, res) => {
  //Collecting data for variables
  //Promise to wait for data
  Promise.all([data]).then(function(result)
  {
    //iterate an array
    for (var i = 0; i < result[0].length; i++)
    {
      var new_record = request.query("INSERT INTO table_test (name, local, date) VALUES ('"+result[0][i].name+"', '"+result[0][i].local+"', '"+result[0][i].date+"')");

      //Promise to wait for insert
      Promise.all([ new_record]).then(function(result)
      {
        console.log("Record number "+i+" inserted");
      }).catch(function(err) {
        console.log(err);
        console.log("Erro collecting data");
     });
    }

    console.log("END");
    res.send('true');

  }).catch(function(err) {
    console.log(err);
    console.log("Erro collecting data");
  });

}

输出为:

END
Record number 1 inserted
Record number 2 inserted
Record number 3 inserted
deadlock error

"END" console.log应该是最后一个日志,而不是第一个。

我该如何解决这种情况。请向我解释我在做什么错。

谢谢

回答如下:

您正在for循环内(您的查询)执行异步操作。 “ END”的输出在循环之外。您正在启动4个Promises,但您无处等待它们解决。因此,首先打印结尾,因为for循环在创建Promises时就完成了(不是真的完成了,但是JavaScript与下一个命令冲突)。

您可以在for循环中等待Promise来解决此问题。代替

Promise.all([ new_record]).then(function(result)

您可以使用

const result = await new_record;

因此您必须将整个功能标记为async

发布评论

评论列表(0)

  1. 暂无评论