内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
使用node js 从一个名为post的表中检索所有的数据库记录,但问题是只有一个记录被检索而不是全部。在PHP中,我可以使用 while()
循环遍历数据库记录来获取所有数据。
目前,我不知道如何在nodejs中整齐地循环访问数据库以获取数据库中的所有记录。一些Stackoverflow的学者建议使用await / async方法,但我不知道要在下面的代码上实现它以使其工作。有人可以帮我解决这个问题。
var connection = require('./config');
module.exports.getpost = function (req, res) {
connection.query('SELECT * FROM posts', function (error, results, fields) {
if (error) {
console.log('error');
res.json({
status : false,
message : 'there are some error with the query'
});
} else {
var postid = results[0].id;
var title = results[0].title;
var content = results[0].content;
var type = -1;
console.log(title);
// Checking user status
connection.query('SELECT count(*) as cntStatus,type FROM like_table WHERE userid= ? and postid=?', [userid,postid], function (error, results, fields) {
if (error) {
console.log('error');
res.json({
status : false,
message : 'there are some error with the query'
});
} else {
var total_count = results[0].cntStatus;
if(total_count > 0){
type = results[0].type;
}
var total_count = results[0].cntStatus;
var result = {
"id" : postid,
"title" : title,
"content" : content,
"type" : type,
"likes" : total_count
};
console.log('query okay');
res.json({
//data:results,
data : result
});
}
});
}
});
}
实际上不需要使用异步/等待,但是如果你想摆脱回调,你需要将连接查询包装到承诺中,或者使用具有promise界面的mysql2 npm。以下是如何使用async / await而不是回调来遍历select中的所有行:
var connection = require('./config');
module.exports.getpost = async function (req, res) {
try {
const queryResult = await query('SELECT * FROM posts');
queryResult.forEach(row => {
console.log(row.title);
})
} catch (err) {
console.log('error');
res.json({
status: false,
message: 'there are some error with the query'
});
}
}