Node js mysql for循环中的存储过程调用

Node js mysql stored procedure call in a for loop

所以,我目前正在使用 mysql npm 包 https://www.npmjs.com/package/mysql。我有一个要求,我必须多次调用一个存储过程,但需要注意的是后续存储过程调用取决于上一个调用。伪代码如下:

let mysql = require("mysql");

let mysqlPoolConnection = mysql.createPool({
      connectionLimit: 20,
      host: '0.0.0.0',
      port: '3306',
      user: 'user1',
      password: 'pwd',
      database: 'mysql_db'
});


for (let index = 0; index < params.length; index++) {
    let sp_ProcedureCall = "CALL sp_StoredProcedure(?, ?, ?, ?)";
    let sp_ProcedureParams = [params[index].firstParam, params[index].secondParam, params[index].thirdParam, params[index].fourthParam];
    // This is where the issue is. I'd like to call the stored procedure once and then once I get a response from it then make subsequent calls. Basically, depending on the previous stored procedure result, I decide whether I continue with subsequent calls or not.
    mysqlPoolConnection.query(sp_ProcedureCall, sp_ProcedureParams, (errorObj, responseObj, fieldsObj) => {

     }
}

NodeJS 是异步的,这意味着您的 for 循环无需等待调用结果即可进行迭代。如果您想 "wait" 获得以前的结果,您需要控制程序的流程。

看看像 async to enabled that type of control flow. From your description, eachSeries() 这样的库可能很适合 - 运行 数组中每个值的函数,一次只有 运行 个。 (或减少,具体取决于您的需要 - 还有其他选择)