2017-05-05 21 views
0

我有僞碼 -如何處理嵌套的包含利用回調sails.js每個循環

foreach(clients){ 
foreach(orderids) 
    { 
    //call asynchronous findOne() 
     if(client_Has_OrderId){ 
     count++; 
     } 
    }//close foreach orderids 
storeInArray(client,count); 
}//close client foreach loop 

我在sails.js新的,不知道如何在sails.js代碼這個我沒有異步編程的經驗。當我以同步方式編碼時,結果不會得到。

結果應該喜歡 -

client1 1 
client2 5 
client3 0 

謝謝。

+0

你可以使用異步()或無極[藍鳥。這不是一個sails.js問題 – Makah

回答

0

我想推薦你看看風帆reference以及concepts section

它總是取決於你的設置:我認爲你已經爲你的訂單設置了一個外鍵(見OneToMany),所以你可以填充你的值並直接在承諾中訪問它們,這將是優化的方式查詢您想要的結果。

ES 5對應的代碼可能看起來像:

請注意,我用的lodash(或下劃線),用於驗證陣列 - 這是在sails.js如果我以前不包括默認情況下,禁用它配置。

Client.find({your:'criteria'}) 
 
    .populate('orders') 
 
    .then(function(clients){ 
 
    
 
    var orderIndex = {}; 
 
    
 
    _.forEach(clients, function(client, index){ 
 
     
 
     if(!_.isArray(client.orders)) { 
 
     orderIndex[client.id] = 0; 
 
     } else { 
 
     orderIndex[client.id] = client.orders.length; 
 
    }); 
 

 
    // do something with [orderIndex] 
 
    
 
    }) 
 
    .catch(function(e){ 
 
    console.log(e); 
 
    })