码迷,mamicode.com
首页 > Web开发 > 详细

关于node.js的思考

时间:2016-07-08 21:47:08      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

今天写了这段用node.js驱动mongoDB访问数据库的代码

function writeDB(receivedText, time, user) {
    var db_host = ‘host‘;
    var port = 27017;
    var username = "usr";
    var pwd = "pwd";
    var db_name = "db";
    var result = "";
    var mongoClient = mongodb.MongoClient;

    mongoClient.connect(db_host, function (err, db) {
        if(err)
        {
            console.log("error-1" + err);
        }
        result += "DB connected.\n";
        console.log(result);

        db.authenticate(username, pwd, function (err, res) {
            if(err)
            {
                console.log("error0" + err);
            }
            result += "DB authenticated.\n";
            console.log(result);

            db.collection(‘note‘).insert({
                "text": receivedText,
                "time": time,
                "user": user
            }, function(err, res){
                if(err)
                {
                    console.log("error1" + err);
                }
                result += "data successfully written.";
                console.log(result);
                db.close();
                console.log("closed");
                return result;
            });
        });
        console.log("function1");
    });
    console.log("function2");
    return result;
}

调用方法为

    var dbResult = writeDB(receivedText, getTime(), "default user");
    console.log(dbResult);
    console.log("finished");
    res.send("succedded");

在实际运行中,log的显示结果为:

function2

finished
DB connected.

function1
DB connected.
DB authenticated.

DB connected.
DB authenticated.
data successfully written.
closed

也就是说,每次在数据库函数中执行callback函数的时候,都会认为这个函数已经执行结束了,继续执行该函数下面的语句,同时执行callback函数。

 

关于node.js的思考

标签:

原文地址:http://www.cnblogs.com/netaddi/p/5654580.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!