简体   繁体   English

使用node.js + mysql的最后一个insertId的全局范围

[英]Global scope of last insertId using node.js + mysql

I am calling function in order to insert some values into a database table using mysql module of node.js . 我正在调用函数,以便使用node.js mysql模块将一些值插入数据库表中。 The function is called inside a for loop and I can get the last insertId of each INSERT query inside the function. 该函数在for循环内调用,我可以在函数内获取每个INSERT查询的最后一个insertId

MY PURPOSE 我的目的

I want to store these id's to an array in to order to use them later in my code but I cannot do that. 我想将这些id's存储到数组中,以便以后在我的代码中使用它们,但是我不能这样做。

- FUNCTION CALL -功能通话

 for(var i=0;i<some_number;i++){
   if (<something is true>){

  var lastid = [];
  //Function calling
  function_a(x, y, z, w,  function(error, result) {
   if(!error){
       lastid.push(result.insertId);
       }
   //To Do
   else{}
  });
 }
}

- FUNCTION -功能

function function_a(a, b, c, d, callback){
//Connection to the DB
const con = mysql.createConnection({
  host: 'host',
  user: 'user',
  password: 'password',
  database: 'database'
});

//DB query
var query = "INSERT INTO my_table (column1, column1, column1, column1) VALUES ('"+a+"', '"+b+"', '"+c+"', '"+d+"')";
con.query(query, (err, rows) => {
 var e = rows.insertId;
 return callback(err, e);
});
con.end(); 
}

The problem is that I cannot use the id's outside the function. 问题是我不能在函数外部使用id。

Any idea how can I do that?Is this about variable scope? 我知道该怎么办吗?这是关于可变范围的吗?

Several problems here, and yes, they are partly about variable scope. 这里有几个问题,是的,它们部分与可变范围有关。

Put var lastid = []; var lastid = []; before the for loop, so you can use it after the loop. 在for循环之前,因此您可以在循环之后使用它。 However, as you have callback mechanism inside the loop, you must wait for the whole loop to finish (all callbacks called from 0 to some_number-1 , in order to have the right values in lastid array. It's a messy thing with callbacks, but you can do it with them or with promises. You can Google for callback handling in for loops. 但是,由于循环中具有回调机制,因此必须等待整个循环结束(所有从0调用到some_number-1回调,以便在lastid数组中具有正确的值。对于回调而言,这很麻烦,但是您可以使用它们或Promise来实现。您可以在for循环中使用Google进行回调处理。

The function function_a is a asynchronous function. 函数function_a是一个asynchronous函数。 In your case you can use async module to do this task: 您可以使用async模块来执行此任务:

var taskIds = Array.apply(null, {length: some_number}).map(Number.call, Number);
var lastid = [];
async.eachLimit(taskIds, 32, function (taskId, done) {
  if (<something is true>) {
    function_a(x, y, z, w,  function(error, result) {
      if(!error){
        lastid.push(result.insertId);
      }
      //To Do
      else{}
      done()
    });
  } else {
    done()
  }
}, function () { 
  // Do some thing with lastid
  console.log(lastid);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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