繁体   English   中英

如何保证 foreach 循环

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM