如何在NodeJS中异步调用MySQL数据库



更新:

我有一个异步函数如下:

async function userHandler(username, displayName, profilePicture, email) {
connection = await connectDB()
await connection.query('USE spyncdb;');
await connection.query('SELECT * FROM users WHERE username = ?', [username], function(error, result, fields) {
if (error) {
console.log(error);
}
if (result) {
if (result != 0) {
console.log('User already in database')
return result[0].user_id;
// Do whatever should be done
} else {
// Add user to database
connection.query('INSERT INTO users (username, displayname, profilePicture, email) VALUES (?, ?, ?, ?)', [username, displayName, profilePicture, email], function(error, result, fields) {
if (error) {
console.log('ERROR');
console.log(error);
}
if (result) {
console.log('user inserted into db');
return;
};
})
}
}
});
}

然后我调用这个函数,并希望存储它的返回值(user_id)。

我从下面调用函数:

async () => {
let user_id = await userHandler(aUser.username, aUser.displayName, 
aUser.profilePicture, aUser.email);

console.log(user_id);
}

但我只得到";未定义的"-为什么?

PS。我使用mysql库进行数据库连接。

好的,所以我终于解决了这个问题。必须做的主要事情是从基于回调的代码切换到更现代的异步/客场方式来处理异步代码,这使得代码不那么复杂,更容易处理和读取。

此外,我还从mysql库切换到了mysql2库,后者更适合异步函数。最后的代码如下:

const mysql2 = require('mysql2/promise');

// Connect to server
const pool = mysql2.createPool({
host     : "ENDPOINT",
user     : "USERNAME",
password : "PASSWORD",
port     : "3306",
database : "DATABASENAME",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0
});
// Function for checking the user in the database
async function checkUser(username, displayName, profilePicture, email) {
const result = await pool.query('SELECT * from users WHERE username = ?', [username]);
if (result[0].length < 1) {
console.log('User not found, adding new user...');
const newResult = await pool.query('INSERT INTO users (username, displayname, profilePicture, email) VALUES (?, ?, ?, ?)', [username, displayName, profilePicture, email]);
return newResult[0].insertId;
}
console.log('User found in DB')
return result[0][0].user_id;
}
// Calling the check function with the input values from the user
async function check() {
let user = await checkUser(aUser.username, aUser.displayName, aUser.profilePicture, aUser.email);
console.log(`user ID is: ${user}`);
}
// Invoking the check function      
check();

有两种解决方案。简单的一个,不要使用回调,使用Promises然后:

aUser.user_id = await userHandler

或者你必须提供一个回调函数并相应地同步你的代码:

function example(cb) {
userHandler(..., function(result) {
cb(user_id);
});
}
example(function(user_id) {
aUser.user_id = user_id;
});

记住,回调驱动的代码实现和使用非常不有趣,所以如果可以的话,如果不是完整的async/await,请转到Promises。

这里的一般规则是如果您的函数进行回调以获得答案,则必须接受可以链接到的回调。回调函数中的return几乎总是被扔进垃圾桶并被忽略

最新更新