簡體   English   中英

Node.js 常量不等待來自異步 function 的響應

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

我是異步/等待的新手,我正在嘗試將“用戶”常量設置為 Node.js 中 MySQL 查詢的返回值。 但是,該常量不會等待 function 的返回值。 如何使用 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...
  }

我在終端得到什么:

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

當您使用帶有回調的db.query時,它不會返回 promise

請嘗試以下代碼

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

請嘗試以下代碼。

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

};

在 jfriend00 的評論之后,我決定讓我的 function 回調 function。 我發現這個答案解釋了如何做到這一點: https://stackoverflow.com/a/31875808/6817961 這行得通!

我現在的代碼:

    // 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