[英]How to promisify a foreach loop
我有这个功能:
remove(data.toString())
function remove(node){
Item.findByIdAndDelete(node).then(()=>{
Item.find({parent: mongoose.Types.ObjectId(node)}).select('_id').then((d)=>{
d.forEach(e => {
remove(e._id)
});
})
})
}
我想承诺它,以便我可以打电话:
remove(data.toString()).then(()=>{console.log('done')})
我怎样才能做到这一点? 任何帮助将不胜感激!
你应该:
map
您从递归调用(而不是forEach
)中获得的承诺数组并将该数组传递给Promise.all
then
回调。function remove(node) {
return Item.findByIdAndDelete(node).then(() => {
return Item.find({parent: mongoose.Types.ObjectId(node)}).select('_id');
}).then(d => {
return Promise.all(d.map(e => {
return remove(e._id)
}));
});
}
使用async
await
语法时,事情可能会变得更容易阅读:
async function remove(node) {
await Item.findByIdAndDelete(node);
let d = await Item.find({parent: mongoose.Types.ObjectId(node)}).select('_id');
return Promise.all(d.map(e => remove(e._id)));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.