简体   繁体   English

map函数完成后如何调用函数

[英]How to call function after map function done

nodejs response returning null array. nodejs 响应返回空数组。 how to return a response after map function done地图功能完成后如何返回响应

  var follow = [];
  User.findOne(
    { _id: id },
  ).then(user => {
    user.following.map(results => {
      User.find({ _id: results.user })
        .exec()
        .then(res => {
          follow.push(res);
     });
    });
    res.json({
      status: true,
      follow // returning null array
    });
  });
};

You need to collect the promises and use Promise.all() to know when they are all done:您需要收集承诺并使用Promise.all()来了解它们何时完成:

User.findOne({ _id: id }).then(user => {
    let promises = user.following.map(results => {
      return User.find({ _id: results.user })
        .exec()
        .then(res => {
          return res;
     });
    });
    Promise.all(promises).then(follow => {
        res.json({
          status: true,
          follow // returning null array
        });
    }).catch(err => {
        console.log(err);
        res.sendStatus(500);
    });
});

Note, there is no reason in your original code to use .map() if you weren't going to return anything from the .map() callback.请注意,如果您不打算从.map()回调中返回任何内容,则在您的原始代码中没有理由使用.map() In my code, I return the promise.在我的代码中,我返回了承诺。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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