我正在尝试使用nodejs创建一个简单的api。但是我无法让nodejs等待sql查询完成。
如何让nodejs等待查询完成?我在使用await / async错误吗?
此处的目标是仅在查询完成后返回d
。
数据库文件
const DB_HOSTNAME = "localhost";
const DB_NAME = "testerino";
const DB_PORT = "8889";
const DB_USERNAME = "root";
const DB_PASSWORD = "root";
const mysql = require('mysql');
const con = mysql.createConnection({
host: DB_HOSTNAME,
user: DB_USERNAME,
password: DB_PASSWORD,
database: DB_NAME,
port: DB_PORT
});
con.connect(function(err) {
if (err) throw err
console.log("Connected to database");
});
async function query(sql){
var results = await con.query(sql);
console.log("foo completed")
return results
}
module.exports = {
con: con,
query: query
}
userLogin文件
const db = require('../../common/database');
function attemptUserLogin(usernameOrEmail, password){
var d = {err: [], res: {}};
console.log("attemptUserLogin");
const foo = db.query("SELECT * FROM users");
console.log("This should wait for foo to complete");
return d;
}
module.exports = {
attemptUserLogin: attemptUserLogin
};
结果
Connected to database
attemptUserLogin
This should wait for foo to complete
foo completed
^它不在等待
答案 0 :(得分:2)
无需将callback
与await
一起使用。请确保您的con.query()
函数向您返回promise
。
async function query(sql){
var results = await con.query(sql); // the result will be stored in results variable ,once the promise is resolved
console.log(results) // the query result will be printed here
return results // the result will be wrapped in promise and returned
}
仅当您的诺言得到解决并且返回的数据存储在结果变量中时,以上函数才会返回结果。
现在,如果您想使用上述功能来获取数据,则可以通过两种方式进行操作
1-使用then
。
query().then(data=>{
console.log(data) // this variable data holds the value you returned from above query function
})
2-使用await调用函数(但必须在异步函数中执行此操作)
async function other()
{
let query_result=await query(); // it will return the data from query function above
}
请参见answer,我已经讨论了查询数据的所有可能情况。
编辑-问题出在您的tryUserLogin函数上,您还必须使其异步
async function attemptUserLogin(usernameOrEmail, password){
var d = {err: [], res: {}};
console.log("attemptUserLogin");
const foo = await db.query("SELECT * FROM users"); // use await here
console.log(foo);// result from query function above
return d;
}
答案 1 :(得分:1)
按如下所示修改您的execute方法,并按照我的方式放置async/await
:
// put async keyword here
const attemptUserLogin = async (usernameOrEmail, password) => {
var d = {err: [], res: {}};
console.log("attemptUserLogin");
// Put await keyword here
const foo = await db.query("SELECT * FROM users");
console.log("This should wait foo.results: ",foo.results);
return d;
}