我正在搞乱node.js,使用Faker,下划线,mysql和randy库将一些测试数据添加到Web应用程序。
到目前为止一直很好 - 但在我的一个循环中,mysql调用每次都失败,但它也无法生成任何错误。我有点难过:
var sql = 'SELECT id FROM mytable WHERE 1';
client.query(sql, function(err, rows, fields){
// loop through results
_.each(rows, function (v, i){
// get the insert id
var id = v.id;
console.log (id); // prints valid ID
// generate other data
var stuff_count = randy.randInt(0,12);
_(stuff_count).times(function(n){
var sql = 'INSERT INTO other_table (linked_id, item_id) VALUES ('+id+','+randy.randInt(1,50)+')';
console.log(sql); // prints sql
client.query(sql, function(err, rows, fields) {
console.log(sql); // prints nothing
if (err){
console.log(sql); // prints nothing
throw err; // prints nothing
}
});
});
});
循环逻辑工作正常,它一直到sql应该对INSERT
执行other_table
的地方 - 但是后面的mysql日志显示没有任何东西击中数据库,没有client.query
块内的调试语句在成功或失败时打印任何内容。
答案 0 :(得分:0)
假设你刚刚运行这个独立的代码,你的代码可能会在它有可能进行插入之前完成。
在_(stuff_count)之后放置一个setTimeout(...,10000).times(...)
通过使用_()。times(),您可以对所有插入进行排队,但不等待完成。您应该使用控制流库来确保等待所有插入完成。