以下快递路由器在做什么?

时间:2017-09-06 11:02:26

标签: javascript node.js express

我所遵循的教程有以下2种路由器方法,用于从db获取文章。

router.param('article', function(req, res, next, slug) {
  Article.findOne({ slug: slug})
    .populate('author')
    .then(function (article) {
      if (!article) { return res.sendStatus(404); }

      req.article = article;

      return next();
    }).catch(next);
});

router.get('/:article', auth.optional, function(req, res, next) {
  Promise.all([
    req.payload ? User.findById(req.payload.id) : null,
    req.article.populate('author').execPopulate()
  ]).then(function(results){
    var user = results[0];

    return res.json({article: req.article.toJSONFor(user)});
  }).catch(next);
});

我对上述方法有两个问题,

  1. Promise.all()如何运作?
  2. 为什么我们需要在router.get()方法中使用router.param()方法重新填充作者字段?

1 个答案:

答案 0 :(得分:1)

  1. Promise.all(iterables) 当您在执行其他任务之前需要完成多个承诺时使用。在给定的情况下

    [ req.payload ? User.findById(req.payload.id) : null, req.article.populate('author').execPopulate() ]

  2. 在传递回调或调用execPopulate之前,不会执行Populate。因此,您的路由器参数实际上不会填充('作者')。 .then只是将它附加到req.article。当您使用相同的路径(' author')再次调用populate时,它会重置上一个填充调用设置的所有查询选项。

  3. 最后在Mongoose文档here中提到了这一点