【问题标题】:How do I wait for the first mysql connection query to resolve before the code moves to the second connection query in same func如何在代码移动到同一 func 中的第二个连接查询之前等待第一个 mysql 连接查询解决
【发布时间】:2021-03-12 12:29:24
【问题描述】:

我正在尝试查询 MySQL 数据库并查看表中是否存在记录 如果确实如此,则在不插入表格的情况下呈现页面 如果没有,则使用另一个查询调用 MySQL 以写入表,然后呈现页面

我认为正在发生的是第一个 connection.query 运行,并且在它呈现页面之前,当记录存在时,它尝试插入到表中并出现以下错误,可能是由于尝试同时呈现但不是当然?任何有关解决此问题的帮助将不胜感激。

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:558:11)

exports.follow = async (req, res) => {
  try {
    pool.getConnection(function (error, connection) {

      if (error) {
        console.log(error);
        return;
      }


       connection.query(checkExists, async (error, results) => {
        if (error)
          throw error;

          return res.status(200).render('search', {
          });
        
      })

      

        connection.query(insertIfDoesNotExist, async (error, results) => {
          if (error) throw error;

          if (loggedin) {
            return res.status(200).render('search', {
            });
          }
        })
      }

    })
  } catch (error) {
    console.log(error);
  }
}

【问题讨论】:

    标签: javascript mysql node.js express connection


    【解决方案1】:

    你是对的,connection.query() 是异步的,所以你最终会遇到竞争条件。 checkExistsinsertIfDoesNotExist 将被同步查询,但它只会在从数据库获得回复时运行其回调(这是异步部分)。

    所以最有可能的是,您最终会同时回电,并尝试两次res.render,这是不正确的。每个 HTTP 请求只能有一个响应。

    那么如何解决呢?你应该嵌套你的回调或使用 await(如果你使用 SQL 驱动程序的承诺版本)到这样的东西

    exports.follow = async (req, res) => {
      try {
        pool.getConnection(function (error, connection) {
          if (error) {
            console.log(error);
            return;
          }
    
          connection.query(checkExists, async (error, results) => {
            if (error) throw error;
            if (!results) // condition to check if it exists here!
              // Only insert this after you've confirmed that it does not exists
              connection.query(insertIfDoesNotExist, async (error, results) => {
                if (error) throw error;
    
                if (loggedin) {
                  return res.status(200).render('search', {});
                }
              });
            return res.status(200).render('search', {});
          });
        });
      } catch (error) {
        console.log(error);
      }
    };
    

    【讨论】:

      猜你喜欢
      • 2018-12-01
      • 2021-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多