如何在for循环中使用猫鼬函数? [英] How can I use mongoose functions inside a for loop?
本文介绍了如何在for循环中使用猫鼬函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法像这样的例子在forEach循环中使用mongoose函数?利用计数器并到达可到达的线
Is there a way I can use mongoose function inside a forEach loop like this example ? making use of the counter and reach the reachable line
idsArray.forEach((itemId,i) =>{
Place.findById(itemId,(err,item)=>{
if(err){
console.log("error")
}
idsArray[i] = {item.id}; // unreachable
})
})
我了解了异步,但是我不知道通过它实现的方式
I read about Async but I couldn't know the way to achieve it through it
推荐答案
更简单:使用db promise映射元素,然后等待所有它们:
Even simpler: map the elements with db promises, then wait for all of them:
var promises= idsArray.map((itemId,i) =>{
return new Promise(function(resolve,reject){
Place.findById(itemId,(err,item)=>{
if(err){
return reject(new Error("some"));
}
resolve(item);
})
});
});
Promises.all(promises).then(function(arr){
console.log(arr);//all results
},function(err){
throw err;
});
这篇关于如何在for循环中使用猫鼬函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文