Node.js常量没有等待来自async函数的响应



我是async/await的新手,我正在尝试在Node.js中设置一个'user'-常量作为MySQL查询的返回值。但是,该常量不会等待函数的返回值。如何使用async和wait将"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发表评论后,我决定将我的函数设置为回调函数。我找到了这个答案来解释如何做到这一点: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!

最新更新