简体   繁体   中英

node.js mysql insert id - how do I expose the insert id outside of the insert query?

Let's say I have a list of values in a json format (or any format) I need to insert into a mysql table. After the insert, I need the result.insertId exposed outside of the mysql.query call. Is there a way to do that? (please, don't ask me why I need this: I know how to work around this. I just need to know if this scenario is possible). Ideally, the description and insert Id of each array item should print to the screen. Instead, I get an empty array. Yes, I know that putting console.log inside of the callback will achieve this. That's not the answer I need. Is it possible to expose the insert Id outside of the callback?

var todos = require('./todos.json');
var mysql = require('mysql');

var mysql_pool = mysql.createPool({
  host : 'localhost',
  user : 'myuser',
  password : 'mypwd',
  database : 'mydb'});

var todoArray = [];

todos.forEach(function(todo) {
   mysql_pool.query("INSERT INTO todos(description) VALUES(?)", todo.description, function(err, result){
        if (err) {
            console.log(" Unable to insert: " + err);
            throw err;
            }
        todoArray.push({description: todo.description, desc_id: result.insertId});
    });
});

console.log(todoArray);

I agree with Brian re asynchronous nature of the queries callback function completing after the console.log command and so no result. Regarding the query loop the method below resolves that by making it sequential. The next data is loaded when the previous query callback is run.

The problem is you can't know when to process the full array with your current method. If you know the last loop you can process the array as the last step in the query callback. Before then you just load the array.

Using an iterator next command will give you the next value and an indicator if its the last loop.

Hopefully something like this:

//use require to get node to parse in the json file as an object
//set todo as iterator type
var todos = require("./path/todos.json")[Symbol.iterator](),
todoArray = [],
todo = todos.next()

//todos.next() iterator cammand returns {done: true/false, value: { }}
//we want to know the end so we can process todoAray

do { 
    mysql_pool.query("INSERT INTO todos(description) VALUES(?)",
        todo.value.description, 
        function(err, result){ 
            if (err) { console.log(" Unable to insert: " + err); throw err; }
            todoArray.push({description: todo.value.description, desc_id: result.insertId})
            todo = todos.next()
            If(todo.done === true){
                console.log(todoArray)
            }
    }); 
}while (!todo.done)

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