猫鼬 + Node.js:异步问题



我的ReadyForReview收藏中有一堆个人资料。每个配置文件都包含一个"user_id_to_review"字段。我想使用 user_id_to_review 将用户集合中的用户信息追加到每个配置文件。

// looking for all ReadyForReview profiles
ReadyForReview.find()
.exec(function(err, profilesReadyForReview) {
    var profilesReadyForReviewArray = [] //array that will be populated with profiles and user info
    // for each profile, figure out what the info for the user is from user table
    for (var i = 0; i < profilesReadyForReview.length; i++) {
        var thisUserProfile = profilesReadyForReview[i].user_id_to_review.toObjectId() // create objectID version of user_id_to_review
        User.find({
                '_id': thisUserProfile
            })
            .exec(function(err, user_whose_profile_it_is) {
                profilesReadyForReviewArray.push({
                    profile: profilesReadyForReview[i],
                    user: user_whose_profile_it_is
                })
            })
        console.dir(profilesReadyforReviewArray) // should be an array of profiles and user info
    }
})

但是,由于异步,User.find 函数中的 i 是错误的。如何获得一系列配置文件和用户信息?

使用异步库来执行循环。https://github.com/caolan/async

// looking for all ReadyForReview profiles
ReadyForReview.find()
.exec(function(err, profilesReadyForReview) {
    var profilesReadyForReviewArray = [] //array that will be populated with profiles and user info
    // for each profile, figure out what the info for the user is from user table
    async.each(profilesprofilesReadyForReview, function(profile, done) {
        var profileId = profile.user_id_to_review.toObjectId() // create objectID version of user_id_to_review
        User.find({
                '_id': profileId
            })
            .exec(function(err, user_whose_profile_it_is) {
                profilesReadyForReviewArray.push({
                    profile: profile,
                    user: user_whose_profile_it_is
                })
                done();
            });
        }, function(){
            console.dir(profilesReadyforReviewArray) // should be an array of profiles and user info
        });
});

最新更新