nodeJS的新手,在理解异步和等待如何工作时遇到了一些问题。这是我的代码正在用来从数据库中获取数据:
const sql = require('mssql');
const config = require('./config');
var Student = require('./student');
module.exports.getAllStudents = async function getAllStudents(){
var studentArray = new Array();
console.log('dbconnection');
var conn = new sql.ConnectionPool(config.dbConfig[0]);
conn.connect()
.then(()=>{
var req = new sql.Request(conn);
req.query('SELECT * from student').then((recordset)=> {
var dataset = recordset.recordset;
for(var index = 0; index<dataset.length; index++){
var student = new Student(dataset[index].student_id , dataset[index].first_name, dataset[index].last_name, dataset[index].student_address , dataset[index].age);
studentArray.push(student);
}
conn.close();
}).catch( (error) =>{
console.log("An error has occured while executing your query ");
console.log(error);
});
})
.catch( (error)=> {
console.log("An error has occured while trying to connect to the database : ");
console.log(error);
});
return studentArray;
}
这是打电话给所有学生的端点:
app.get('/getAllStudents' , function(req , res){
var studentArr = new Array();
studentArr = query.getAllStudents();
console.log('====================================');
//console.log(studentArr); //this prints undefined
//console.log('length:======' + studentArr.length);
//var json = JSON.stringify(studentArr);
res.status(200);
res.send('got all students');
})
试图了解如何解决该错误,需要做些什么来等待我的查询获得结果,然后打印出学生数组。有人可以向我解释需要做什么以及为什么它不起作用吗?
答案 0 :(得分:0)
因为它是异步的,所以您应该返回一个承诺,然后resolve()
返回结果
const sql = require('mssql');
const config = require('./config');
var Student = require('./student');
module.exports.getAllStudents = function getAllStudents() {
return new Promise((resolve, reject) => {
var studentArray = new Array();
console.log('dbconnection');
var conn = new sql.ConnectionPool(config.dbConfig[0]);
conn.connect()
.then(()=>{
var req = new sql.Request(conn);
req.query('SELECT * from student').then((recordset)=> {
var dataset = recordset.recordset;
for(var index = 0; index<dataset.length; index++){
var student = new Student(dataset[index].student_id , dataset[index].first_name, dataset[index].last_name, dataset[index].student_address , dataset[index].age);
studentArray.push(student);
}
resolve(studentArray);
conn.close();
}).catch( (error) =>{
console.log("An error has occured while executing your query ");
console.log(error);
reject(error);
});
})
.catch( (error)=> {
console.log("An error has occured while trying to connect to the database : ");
console.log(error);
reject(error);
});
});
}
然后将async
添加到函数中,并将await
添加到query.getAllStudents()
app.get('/getAllStudents' , async function(req , res){
var studentArr = new Array();
studentArr = await query.getAllStudents();