在返回结果之前,nodejs不等待异步功能完成

特雷弗·伍德(Trevor Wood)

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

^它不在等待

舒布

有没有必要使用callback具有await。使确保您的con.query()函数返回promise在此,向您suceed。

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
    }

仅当您的诺言得到解决并且返回的数据存储在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
}

看到这个答案,我已经讨论了所有可能的查询数据的情况。

编辑-问题出在您的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;
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章