如何防止Node.js中的非阻塞?

时间:2015-07-11 16:54:41

标签: javascript node.js

这是我的代码的一部分。

var project_url;
project_url = getProjectUrl(req,name);

var collection = db.get('project');     
collection.insert({
     "id" : projectId,
     "name" : name,
     "url" : project_url
}, function(err,doc){
     if(err){
         res.send("There was a problem");
     }
});

var collection2 = db.get('project_details');
collection2.insert({
    "id" : projectId,
    "media" : media
}, function(err,doc){
     if(err){
        res.send("There was a problem");
     }
});

将Node.js与MongoDB一起使用,我想将数据插入数据库AFTER函数getProjectUrl,它返回一个字符串值,已经完成。但是,它以异步方式运行,以便在getProjectUrl返回值之前执行collection.insert和collection2.insert。因此,当我检查数据库时,project_url为null。如何在getProjectUrl返回值后执行插入?

1 个答案:

答案 0 :(得分:0)

使用回调功能getProjectUrl,例如

function getProjectUrl(req, name, callback) {
    var result = 'foo'; // I'm not sure how you get it

    callback(result);
}

然后

getProjectUrl(req, name, function(project_url) {
    var collection = db.get('project');     
    collection.insert({
         "id" : projectId,
         "name" : name,
         "url" : project_url
    }, function(err,doc){
         if(err){
             res.send("There was a problem");
         }
    });

    var collection2 = db.get('project_details');
    collection2.insert({
        "id" : projectId,
        "media" : media
    }, function(err,doc){
         if(err){
            res.send("There was a problem");
         }
    });
});