NodeJS用knex迭代速度太快

我在查询(knexjs.org)的for循环有一些困难。 让我们开始如何遍历我的数组。 我的数组看起来像这样:

[ { module_id: 9, able: '1', will: '1' }, { module_id: 9, able: '1', will: '1' }, { module_id: 2, able: '1', will: '1' }, { module_id: 2, able: '1', will: '1' }, { module_id: 4, able: '1', will: '1' }, { module_id: 4, able: '1', will: '1' }, { module_id: 1, able: '1', will: '1' }, { module_id: 1, able: '1', will: '1' }, { module_id: 8, able: '1', will: '1' }, { module_id: 8, able: '1', will: '1' }, { module_id: 7, able: '1', will: '1' }, { module_id: 7, able: '1', will: '1' }, { module_id: 5, able: '1', will: '1' }, { module_id: 5, able: '1', will: '1' }, { module_id: 3, able: '1', will: '1' }, { module_id: 3, able: '1', will: '1' }, { module_id: 6, able: '1', will: '1' }, { module_id: 6, able: '1', will: '1' } ] 

那么“有趣”的部分就来了:

 for(var i = 0; i < obj.length; i++) { var object = obj[i]; console.log("has object", object); db.knex('interests').where({ inventory_id: inventory_id, module_id: object.module_id }).select().limit(1).then(function (result) { console.log("MODULE ID", object.module_id); if (result.length == 0) { db.knex('interests').insert({ inventory_id: inventory_id, module_id: object.module_id, could: object.able, would: object.will }).then(function (a) { }); } else { db.knex('interests').where({ inventory_id: inventory_id, module_id: object.module_id }).update({ could: object.able, would: object.will }).then(function (a) { }); } }); } 

代码的作用如下:

  • 遍历数组
  • 查询数据库
  • 如果没有结果,创build一些东西
  • 如果结果,更新的东西

只有一个问题。 for循环太快了。 换句话说, 查询太慢了。 为什么? 因为object.module_id始终是数组中的最后一个module_id

我如何确保它使用for循环中的module_id,而不是上一次迭代的variables?

其实不是Node太快了。 这是因为查询asynchronous工作。

该进程不会等待查询完成以继续循环。 当他们执行时,循环已经结束。

我build议将所有的查询/更新包装在函数中作为参数:链接你的callback方法,以便它们能够按预期工作

  var queryinterest = function(object){ db.knex('interests').where({ inventory_id: inventory_id, module_id: object.module_id }).select().limit(1).then(function (result) { if (result.length == 0) { insertInterest(object) } else { updateInterest(object) }) } 

然后在主循环中调用它们。

 for(var i = 0; i < obj.length; i++) { queryInterests(obj[i]) }); } 

编辑:这篇文章是澄清为什么以及如何工作asynchronous伟大:

Nodejsasynchronous混乱