node.js mysql insert id – 如何在插入查询之外公开insert id?

比方说,我有一个json格式的值列表(或任何格式),我需要插入到一个MySQL表。 插入之后,我需要在mysql.query调用之外暴露的result.insertId。 有没有办法做到这一点? (请不要问我为什么需要这个:我知道如何解决这个问题,我只需要知道这个scheme是否可行)。 理想情况下,每个数组项目的说明和插入标识应打印到屏幕上。 相反,我得到一个空的数组。 是的,我知道把console.log 放在callback里面是可以实现的。 这不是我需要的答案。 是否有可能在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); 

我同意Brian重新查询asynchronous性质的查询callback函数完成后console.log命令等没有结果。 关于查询循环,下面的方法通过使其顺序来解决这个问题。 当前一个查询callback运行时,下一个数据被加载。

问题是你无法知道什么时候用你当前的方法处理完整的数组。 如果您知道最后一个循环,则可以将该数组作为查询callback的最后一步。 在那之前你只需加载数组。

使用iterator next命令会给你下一个值和一个指示符,如果它是最后一个循环。

希望这样的事情:

 //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)