1

在我的控制器中的“视图”方法之前使用过,node-async但我想尝试使用q.

我目前正在尝试转换它

exports.view = function (req, res) {
    var category = req.params.category,
        id = req.params.id,
        ip = req.connection.remoteAddress,
        slug = req.params.slug,
        submission,
        userId = typeof req.session.user !== 'undefined' && req.session.user.id ? req.session.user.id : null,
        views;
var getSubmission = function (submissionId, callback) {
    Submission.getSubmission({
        id: submissionId
    }, function (err, submission) {
        if (err) {
            callback(err);
        } else if (submission) {
            callback(null, submission);
        } else {
            callback(err);
        }
    });
};


async.waterfall([

function (callback) {
    getSubmission(id, callback);
},

function (submission, callback) {
    res.render('submission', {
        title: submission.title + ' -',
        submission: submission
    });
}]);

要使用 q... 我开始做类似的事情:

var getSubmission = function(id) {
  return Submission.getSubmission({
    id : submissionId
  }).then(function(submission) {
    return submission;
  });
};

q.fcall(getSubmission).then(function(submission) {
  console.log(submission);
});

但它并没有像我预期的那样工作。我在这里做错了吗?我怎样才能做到这一点?

4

1 回答 1

1

Submission.getSubmission对数据库的调用吗?那么你不能“链接”承诺。您必须使用以下deferred方法:

var getSubmission = function(id) {
  var deferred = Q.defer();
  Submission.getSubmission({
    id: id
  }, function(err, data){
    if (err) {
      deferred.reject(err);
    } else {
      deferred.resolve(data);
    }
  });
  return deferred.promise;
}

getSubmission(some_id).then(successCallback, failureCallback); 

您还可以Q#denodeify使用 nodejs 样式的回调 ( function(err, data)) 将函数转换为基于 Promise 的函数。因此,上述也可以通过以下方式实现:

getSubmissionPromise = Q.denodeify(Submission.getSubmission);
getSubmissionPromise({id: some_id}).then(successCallback, failureCallback);
于 2013-06-07T05:20:34.713 回答