我正在使用 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
.
我需要把它变成一个承诺吗?可能不是因为我只是循环(同步)通过一个集合?哈尔普请。