如何处理嵌套的包含利用回调sails.js每个循环
问题描述:
我有伪码 -如何处理嵌套的包含利用回调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
谢谢。
答
我想推荐你看看风帆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);
})
你可以使用异步()或无极[蓝鸟。这不是一个sails.js问题 – Makah