javascript - 如何承诺一个foreach循环
问题描述
我有这个功能:
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)));
}
推荐阅读
- docker - Windows 10 上的 Docker 中的 Docker
- menu - 移动子菜单
- python - 新手 Python 支持请求
- formatting - tinymce-如何禁用粘贴格式选项弹出?
- python - 自定义数据集上的 tensorflow 对象检测 api eval
- java - responseEntity 的问题。MockMvc.Perform() 给出 200 状态码,即使 ResponseEntity.HttpStatus 是 201
- javascript - 如何将内联 babel 脚本转换为 JS
- python - Django Daphne 大文件上传
- mysql - 如果任一表中的某个日期,如何从两个表中返回一条记录
- go - 如何实现服务器端超时?(对 http.Server 超时感到困惑)