在使用Q的延迟/保证时组合同步功能

时间:2013-06-09 10:34:32

标签: javascript node.js callback promise q

我正在使用Q库进行一系列延迟/承诺工作正常,但是一旦我在一个链式回调中找回了我的一些数据,我想以某种方式操纵它。

E.g。

   var getFavorites = function(submissionId) {
  deferred = Q.defer();

  Submission.getFavorites({
    submissionId : submissionId
  }, function(err, favorites) {
    if (err) {
      deferred.reject(err);
    } else {
      deferred.resolve(favorites);
    }
  });
  return deferred.promise;
};

var didUserFavorite = function(favorites) {
  var didUserLike;
  deferred = Q.defer();

  favorites.forEach(function(favorite) {
    if (favorite.user_id === userId) {
      didUserLike = true;
      deferred.resolve(didUserLike);
    } else {
      didUserLike = false;
      deferred.resolve(didUserLike);
    }
  });
  return deferred.promise;
};

getSubmissionPromise = Q.denodeify(Submission.getSubmission);
getCommentsPromise = Q.denodeify(Submission.getComments);
getViewsCountPromise  = Q.denodeify(Submission.getViewsCount);
getCommentLikesPromise = Q.denodeify(Submission.getCommentLikes);
getFavoritesPromise = Q.denodeify(Submission.getFavorites);

getSubmissionPromise({ id: id }).then(function(submission) {
  var submissionId = submission._id.toString();

  return getViewsCountPromise({ submissionId : submissionId }).then(function(viewsCount) {
    return getFavoritesPromise({ submissionId : submissionId }).then(function(favorites) {


      // WANT TO MANIPULATE IT HERE:
      //return didUserFavorite({ favorites : favorites }).then(function(didUserFavorite) {


        return getCommentsPromise({ submissionId : submissionId }).then(function(comments){
          return getCommentLikesPromise({ submissionId : submissionId }).                        then(function(commentLikes) {

            comments.forEach(function(comment) {
              var likes = _.where(commentLikes, { comment_id : comment._id.toString() }),
                  likeUserId;

              likes.forEach(function(like) {
                likeUserId = like.user_id.toString();

                if (likeUserId === userId) {
                  comment.didUserLike = true;
                  comment.userLikeId = like._id.toString();
                }
              });

              if (likes && likes !== 'undefined') {
                comment.likes = likes;
              }
            });

            renderSubmission(submission, comments, viewsCount, favorites);
          });
        });
    //  });
    });
  });

所有承诺都有效,但我想致电didUserFavorite,然后让它继续下一个延迟/承诺getCommentsPromise

我需要将其纳入承诺吗?可能不是因为我只是通过集合循环(同步)? Halp plz。

1 个答案:

答案 0 :(得分:0)

问题中没有任何内容表明didUserFavorite()不是同步,因此返回true / false就足够了。

这样的事情可能是:

var didUserFavorite = function(favorites) {
    favorites.forEach(function(favorite) {
        if (favorite.user_id === userId) {
            return true;
        }
    });
    return false;
};

getSubmissionPromise()内,您可以按如下方式调用didUserFavorite()

if(didUserFavorite(favorites)) {
    .....
}