2015-11-12 66 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