0

我正在使用 Q 库做一堆延迟/承诺,它们工作得很好,但是一旦我在一个链式回调中取回我的一些数据,我想以某种方式操作它。

例如

   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.

我需要把它变成一个承诺吗?可能不是因为我只是循环(同步)通过一个集合?哈尔普请。

4

1 回答 1

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)) {
    .....
}
于 2013-06-09T16:46:09.047 回答