我正在尝试用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
}
用户登录文件
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
^ 不等了
最佳答案
无需将 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
}
只有当您的 Promise 得到解决并且返回的数据存储在 results 变量中时,上述函数才会返回结果。
现在如果你想使用上面的函数来获取数据,你可以通过两种方式来实现
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 ,我已经讨论了查询数据的所有可能情况。
编辑 - 问题出在您的 attemptsUserLogin 函数上,您也必须使其异步
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;
}
关于node.js - Nodejs 在返回结果之前不等待异步函数完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58656431/