【问题标题】:nodejs not awaiting for async func to complete before returning resultsnodejs在返回结果之前不等待异步函数完成
【发布时间】:2019-11-01 08:52:06
【问题描述】:

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

^ 它没有等待

【问题讨论】:

  • 这个函数试图返回什么,我看不到你期望返回查询结果?

标签: node.js


【解决方案1】:

没有必要使用 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,我已经讨论了查询数据的所有可能情况。

编辑 - 问题在于您的尝试用户登录功能,您还必须使其异步

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;
}

【讨论】:

  • 很好,这就是返回一个承诺。越来越近。在promise完成之前如何防止函数返回?
  • 查看更新的答案,查询函数在promise解决之前不会返回结果(等待)
  • 我试了一下,但出现错误。 async function query(sql){ var results = await con.query(sql); return results } async function other(sql){ let queryResult = await query(sql); return queryResult; }您能否提供完整的代码片段以确保我正确实施?
  • 更新答案请查收。
  • 我弄错了,等我更新我的答案
【解决方案2】:

修改您的执行方法,如下所示,并按照我的方式输入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;
}

【讨论】:

  • 它说我不能在 db.query 上使用 await
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 2017-07-12
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多