由于异步js

时间:2017-03-21 14:02:35

标签: javascript node.js mongodb asynchronous

为DB中的每个userModel调用整个函数allPrototypes(userModel, callback),比方说100次。

我的问题:由于异步JS,仅使用100个userModel中的最后一个调用函数addJobToUser(userId, jobId)。 因此,addJobToUser被调用100次,但不是userModel 1到100,而是每次使用userModel 100(正如您在我的评论中看到的那样)。 我可以想象问题是异步JS。

你们有解决方案吗?

function allPrototypes(userModel, callback){
    // HERE console.log() -> USER MODELS 1-100 
    var MongoClient = mongo.MongoClient;
    var url = 'mongodb://localhost:27017/uniyapp';

    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var cursor = db.collection('jobprototypes').find();
        cursor.each(function (err, doc) {
            if(doc != null){
                console.log(userModel.id);
                // create prototypeModel
                var jobPrototypeModel = new prototype.emptyPrototype();
                jobPrototypeModel.attributes = doc['attributes'];
                jobPrototypeModel.contributors = doc['contributors'];
                jobPrototypeModel.id = doc['_id'];
                // now calculate the similarity between prototypemodel and usermodel
                // HERE console.log() -> USER MODELS 1-100 
                console.log(callback(jobPrototypeModel, userModel));

                if(callback(jobPrototypeModel, userModel) <= threshold){
                    addJobToUser(userModel.id, jobPrototypeModel.id);
                }
            }
        });
        db.close();
    });
}

function addJobToUser(userId, jobId){
    var MongoClient = mongo.MongoClient;
    var url = 'mongodb://localhost:27017/uniyapp';

    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        db.collection('jobusers').update({_id:userId}, {'$set' : {jobs: ['nevermind']}});
        db.close();
    });
}

0 个答案:

没有答案