简体   繁体   中英

How do I wait for the first mysql connection query to resolve before the code moves to the second connection query in same func

Im trying to query a MySQL database and see if a record exists in a table if it does then render page without inserting to a table if it does not then call MySQL with another query to write to a table and then render page

What I believe is happening is that the first connection.query runs and before it renders the page when the record exists it tries to insert to table and errors with the below, maybe due to trying to render at the same time but not sure? Any help on solving this will be appreciated.

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);
  }
}

You're right, connection.query() is asynchronous, so you've end up with race condition. checkExists and insertIfDoesNotExist will be queried synchronously, but it will only run its callback when it gets a reply from the database (this is the async part).

So most probably, you end up calling both call back, and trying to res.render twice, which is not correct. Each HTTP request can only have one response.

So how to solve this? You should nest your callback or use await (if you use a promise version of SQL driver) to something like this

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);
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM