无法返回值(我认为是范围问题)
2012-10-12
110
我的大学课程刚刚开始讲授 mongodb,我们有一个作业要做。到目前为止一切似乎都进展顺利,但我在 response.write 中遇到了返回值的问题。范围问题似乎总是困扰着我。代码如下:
var querystring = require("querystring"),
fs = require("fs"),
mongodb = require('mongodb'),
server = new mongodb.Server('localhost',27017, {auto_reconnect: true}),
db = new mongodb.Db('testdb',server);
db.createCollection('testCollection', {safe : true}, function(err, collection){});
function createData(response, postData) {
var fname = querystring.parse(postData).fname;
var lname = querystring.parse(postData).lname;
var phone = querystring.parse(postData).phone;
var info = {'fname':fname,'lname':lname,'phone':phone};
var infojson = JSON.stringify(info);
var infojson = JSON.parse(infojson);
db.open(function(err, db) {
if(!err) {
db.collection('testCollection', function(err, collection) {
collection.insert(infojson, {safe : true}, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
db.close();
}
});
});
}
return result;
});
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("You have added " + result + " to the database.");
response.end();
}
这是我收到的错误:
/home/ubuntu/151_final/requestHandlers.js:36
response.write("You have added " + result + " to the database.");
^
ReferenceError: result is not defined
at Object.createData [as /createData] (/home/ubuntu/151_final/requestHandlers.js:36:40)
at route (/home/ubuntu/151_final/router.js:4:19)
at IncomingMessage.<anonymous> (/home/ubuntu/151_final/server.js:18:4)
at IncomingMessage.EventEmitter.emit (events.js:85:17)
at IncomingMessage._emitEnd (http.js:366:10)
at HTTPParser.parserOnMessageComplete [as onMessageComplete] (http.js:149:23)
at Socket.socket.ondata (http.js:1690:22)
at TCP.onread (net.js:402:27)
1个回答
我认为你应该这样做
db.open(function(err, db) {
if(!err) {
db.collection('testCollection', function(err, collection) {
collection.insert(infojson, {safe : true}, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
db.close();
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("You have added " + result + " to the database.");
response.end();
}
});
});
}
});
这不是范围问题,只是调用是异步的,结果未定义,因为行
response.write("You have added " + result + " to the database.");
立即执行,它不会等待其他函数返回
Nicola Peluchetti
2012-10-12