简体   繁体   中英

How to increment external variable value within MySQL Query in NodeJS

I'm developing an API using NodeJS and MySQL.

The create API takes a Request as an object and executes the queries one by one inside the for statement.

And I created a variable called createCnt externally to count the success of the query, and I want to use this value when sending a response.

But since the current code is callback, the order of execution is not guaranteed.

Therefore, if you print createCnt outside of a query, -1 always appears.

How can I increment a variable outside the query inside the query?

create API

exports.create = async (req, res, next) => {
  const { userId } = req.decoded;
  const { createList } = req.body;

  let createCnt = undefined;

  try {
    createCnt = -1;

    for (let i = 0; i < createList.length; i++) {
      const { content, color, date, colorLevel } = createList[i];

      let sql = `INSERT INTO post (content, color, date, colorLevel, userId) VALUES (?, ?, ?, ?, ?)`;

      Post.query(
        sql,
        [content, color, date, colorLevel, userId],
        async (err, result) => {
          if (err) {
            return next(err);
          }
          return await (createCnt += 1); // increase OK
        }
      );
    }
  } catch (error) {
    console.log(error);
  } finally {
    console.log(createCnt); // always "-1"
  }
};

The problem is that Post.query is async. You should use it with await in order to to get it working as you expected.

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