2015-11-12 55 views
1

我在查询(knexjs.org)的for循环中遇到了一些困难。让我们开始如何遍历我的数组。我的阵列看起来像这样:NodeJS用knex迭代速度太快

[ { 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) { 
       }); 
      } 
     }); 
    } 

什么代码所做的是以下几点:

  • 迭代通过数组
  • 查询数据库
  • 如果没有结果,请创建一些东西
  • 如果结果,更新内容

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

我该如何确保它使用for循环中的module_id,而不是上次迭代时给出的变量?

回答

1

实际上,它并不是Node太快。这是因为查询异步工作

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

我建议 包装与数据作为参数的函数您所有的疑问/更新: 链接你的回调方法,使他们能够按照预期

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]) 
     }); 
    } 

编辑:这个职位是伟大的澄清为什么和如何工作的异步:

Nodejs asynchronous confusion

+0

我们快到了,感谢您的帮助迄今为止...然而,在queryinterest,'返回q_result'返回未定义,因为查询尚未完成...那么如何解决? – Thijmen

+0

哎呦,我想我犯了一个'q_restult'而不是'q_result',我编辑了我的代码! –

+0

这也行不通。在再次编辑“q_result = result” – Thijmen