node.js—for循环中的node js mysql存储过程调用

lskq00tm  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(409)

所以,我目前正在使用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) => {

     }
}
xn1cxnb4

xn1cxnb41#

nodejs是异步的,这意味着for循环在不等待调用结果的情况下进行迭代。如果要“等待”以前的结果,则需要控制程序的流。
看看像async这样的库,可以启用这种类型的控制流。根据您的描述,eachseries()可能非常适合为数组中的每个值运行一个函数,并且一次只运行一个(或减少,取决于你的需要-还有其他选择)

相关问题