mysql插入nodejs时for循环中的代码执行顺序

Code execution order in for loop when mysql insert nodejs

我有一个非常简单的问题,我好几天都无法解决。我写了下面这个简单的代码块来举个例子。

var mysql = require("mysql")

var connection = mysql.createConnection({
  host: "localhost",
  user: "***",
  password: "***",
  database: "***",
  charset: "utf8mb4"
})

var testArr = ["banana", "apple", "orange", "strawberry"]

for (let fruit of testArr) {
    console.log("fruit check:" + fruit)

    var fruitName = connection.escape(fruit)

    var sql = "INSERT INTO test (name) VALUES (" + fruitName + ")";

    connection.query(sql, function (err, result) {
        if (err) throw err;
        console.log("1 record inserted");
    });
}

我在这里唯一想做的就是进入for循环后实际按顺序进行。目前控制台端如下;

fruit check:banana
fruit check:apple
fruit check:orange
fruit check:strawberry
1 record inserted
1 record inserted
1 record inserted
1 record inserted

我希望它是这样的:

fruit check:banana
1 record inserted
fruit check:apple
1 record inserted
fruit check:orange
1 record inserted
fruit check:strawberry
1 record inserted

连接 mysql 时尝试使用 promise,并使用 async/await。

你可以得到大概的答案here

async - awaitmysql2 试试这个方法。
我将查询更改为准备好的语句。

const mysql = require('mysql2/promise');

const loadData = async () => {
  try {
    var connection = await mysql.createConnection({
      host: 'localhost',
      user: '***',
      password: '***',
      database: '***',
      charset: 'utf8mb4',
    });

    var testArr = ['banana', 'apple', 'orange', 'strawberry'];

    for (let fruit of testArr) {
      console.log('fruit check:' + fruit);
      var sql = 'INSERT INTO test (name) VALUES (?)';
      await connection.execute(sql, [fruit])
      console.log('1 record inserted');
    }
  } catch (err) {
    throw err; // Or do something else with the error...
  }
};

loadData();