关于node.js的思考
今天写了这段用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函数。