简体   繁体   English

Node.js 常量不等待来自异步 function 的响应

[英]Node.js constant is not waiting for response from async function

I am new to async/await and I'm trying to set a 'user'-constant as the return value of a MySQL query in Node.js.我是异步/等待的新手,我正在尝试将“用户”常量设置为 Node.js 中 MySQL 查询的返回值。 However, the constant does not wait for the return value of the function.但是,该常量不会等待 function 的返回值。 How do I use async and await to set 'user' to the return value of the SQL query?如何使用 async 和 await 将 'user' 设置为 SQL 查询的返回值?

// Should return a user object
const getUserByUsername = async (username, db) => {

  const QUERY = `SELECT * FROM ${table_name} WHERE username = '${username}'`;
    
    const user = await db.query(QUERY,
      async (err, result) => {

        if (!err) {

          console.log("name in SQL function: " + result[0].username);
          return await result[0];

        } else {
          console.log(err);
        }
      }
    );
    return user;
};

// Does stuff with the user object
const authenticateUser = async (username, password, done) => {

    const user = await getUserByUsername(username, db);
    console.log("name in main function: " + user.username);

    // Trying to do stuff with the user object...
  }

What I get in the terminal:我在终端得到什么:

name in main function: undefined

UnhandledPromiseRejectionWarning: Error: data and hash arguments required
at Object.compare
at /app/node_modules/bcrypt/promises.js:29:12
at new Promise (<anonymous>)
at Object.module.exports.promise
etc.....


name in SQL function: john

When you use db.query with a callback, it does not return a promise当您使用带有回调的db.query时,它不会返回 promise

Try the following code instead请尝试以下代码

const getUserByUsername = async (username, db) => {
    const QUERY = `SELECT * FROM ${table_name} WHERE username = '${username}'`;
   
    const result = await db.query(QUERY);
    console.log("name in SQL function: " + result[0].username);
    return result[0];
};

Please try the below code.请尝试以下代码。

const getUserByUsername = async (username, db) => {
try {
    const QUERY = `SELECT * FROM ${table_name} WHERE username = '${username}'`;

    const user = await db.query(QUERY, async (err, result) => {
        if (err) {
            throw err;
        }
        if (result && result.length) {
            return result[0];
        }
        throw new Error(`User with username ${username} not found`);
    });

    console.log(`name in SQL function: ${user.username}`);
    return user;

} catch (error) {
    console.log(error);
    throw error; 
}

};

After jfriend00's comment, I decided to make my function a callback function.在 jfriend00 的评论之后,我决定让我的 function 回调 function。 I found this answer explaining how to do it: https://stackoverflow.com/a/31875808/6817961 .我发现这个答案解释了如何做到这一点: https://stackoverflow.com/a/31875808/6817961 This worked!这行得通!

My code now:我现在的代码:

    // Function returns a user object
      const getUserByUsername = (username, callback) => {

        const QUERY = `SELECT * FROM ${db_name} WHERE username = '${username}'`;

        db.query(QUERY, (err, result) => {

          if (!err) {

            if (result.length > 0) {
              return callback(null, result[0]);

            } else {
              err = "No user with that username";
              return callback(err, null);
            }

          } else {
            return callback(err, null);
          }
        });
      };

 // Then this function does stuff with the callback
  const authenticateUser = (username, password, done) => {

    getUserByUsername(username, async (err, result) => {

      if (err) {
        console.log(err);
        return done(null, false, { message: err });

      } else {
        const user = result;
        // result will now return the user object!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM