[英]Using promises for db and server
Im still learning js, but im trying to write a basic server in nodejs. 我仍在学习js,但我试图在nodejs中编写基本服务器。 The server is supposed to take a query and then return a JSON from a db.
服务器应该进行查询,然后从数据库返回JSON。
Im trying to use promises but can get my head around this. 我试图使用承诺,但可以解决这个问题。 My server returns an empty reply.
我的服务器返回一个空答复。 So what am i doing wrong?
那我在做什么错?
My server file so far (simplified): 到目前为止,我的服务器文件(简体):
http.createServer(function (request, response) {
if (request.method === "GET") {
...
var dbRes = dbFunc.getFromDB(query);
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(dbRes));
}
}).listen(port);
My db file so far (simplified): 到目前为止我的数据库文件(简体):
exports.readHandeler = function (query) {
var promise = new Promise(function(resolve, reject) {
db.collection('data').find(query).toArray(function(err, res) {
if (err) {
throw err;
reject(-1);
}
resolve(res);
}
});
promise.then(function(result) {
return result;
}, function(err) {
return -1;
});
}
My server returns an empty reply.
我的服务器返回一个空答复。 So what am i doing wrong?
那我在做什么错?
Your dbRes
will be undefined
since you're expecting a response from async promise execution. 您的
dbRes
将是undefined
因为您期望异步诺言执行产生响应。 You need to send response only after promise resolves. 仅在承诺解决后才需要发送响应。
Making this change to your code 对您的代码进行更改
http.createServer(function (request, response) {
if (request.method === "GET") {
...
dbFunc.getFromDB(query).then((dbRes) => {
response.statusCode = 200;
response.setHeader('Content-Type', 'application/json');
response.end(JSON.stringify(dbRes));
}).catch((err) => {
console.log('err', err.stack);
});
}
}).listen(port);
Also, you need to return Promise in db execution part. 另外,您需要在数据库执行部分返回Promise。
exports.readHandeler = function (query) {
return new Promise(function (resolve, reject) {
db.collection('data').find(query).toArray(function (err, result) {
if (err) {
return reject(err); // or -1 based on your need
}
return resolve(result);
});
});
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.