将请求数据传递给 Q promise

Passing req data into Q promise

我觉得 Javascript 闭包有问题?我有一个 Express + Mongoose 网络应用程序,并且正在使用 Q 库来实现 Promises。

我想知道是否可以将请求数据传递到承诺链,以便我可以成功执行以下代码。

目前,我无法设置 review.reviewerreview.application。目前我能想到的唯一解决方案是将请求数据附加到 req.body 对象,以便所有这些都在 Review.create 上处理(参见替代解决方案代码)。不过,我不确定这是否是一个理想的解决方案,也不确定是否可以将请求数据传递到承诺中。

create: function(req, res) {
    console.log('Creating obj');

    Review.create(req.body).then(function(review) {
      Q.all([
        function() {
          review.reviewer = req.user.id;
          review.application = req.params.applicationId;
          return review.save();
        },
        User.findByIdAndUpdate(review.reviewer, {$push: {reviews: review._id}}).exec(),
        Application.findByIdAndUpdate(review.application, {$push: {reviews: review._id}}).exec(),
      ]).then(function() {
        req.flash('messages', {
          style: 'success', 
          type: 'Success',
          text: 'Your review has been submitted!',
        });
        res.redirect('/applications');
      }, function(err) {
        req.flash('messages', {
          style: 'danger', 
          type: 'Error',
          text: 'Something went wrong submitting the application!',
        });
        res.redirect('/applications');
      })
    });
  }

备选方案代码:

req.body.reviwer = req.user.id;
req.body.application = req.params.applicationId;
Review.create(req.body).then(...)

据我了解,您犯了两个错误:

  • Q.all 前面应该有一个 return 否则,它会假设 return null 即不会等到 Q.all 完成
  • Q.all的第一个元素是一个函数,我很确定它必须是一个承诺,

我已经把功能细节放在外面了,希望它现在能用:

    ...
    Review.create(req.body).then(function(review) {
      review.reviewer = req.user.id;
      review.application = req.params.applicationId;
      return Q.all([
        review.save(),
        User.findByIdAndUpdate(review.reviewer, {$push: {reviews: review._id}}).exec(),
        Application.findByIdAndUpdate(review.application, {$push: {reviews: review._id}}).exec(),
      ]).then(function() {
    ...