node.js - Nodejs 在返回结果之前不等待异步函数完成

标签 node.js

我正在尝试用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

^ 不等了

最佳答案

无需将 callbackawait 一起使用。确保您的 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/

相关文章:

javascript - 数据库查询在带有 oracledb 的 node.js 中返回未定义的值

node.js - 批处理文件调用 Node.js - 如何从 Node 设置 ERRORLEVEL

node.js - React 不显示使用 Multer 上传的图像

node.js - 如何在node js中导入boxicons

javascript - 使用 Electron 显示或读取操作系统或系统中存在的所有文件和文件夹

javascript - 在私有(private)注册表上发布和安装 npm 包的问题

json - Azure 网站实例未运行 Package.json 中定义的 Node 版本

node.js - fs.writeFileSync 在 Windows 上给出 ENOENT 错误

javascript - 使用标志启动时,Docker SIGTERM 未传送到 node.js/coffee 应用程序

node.js - 使用带有环回的非休息调用 (Strongloop)