mysql - await 和 async 在递归函数中不起作用
问题描述
我正在尝试将代码连接到 MySQL。当第一次尝试连接失败时,我希望它重新尝试连接。所以,这段代码使用了递归函数。
此代码包含数据库连接过程。
const mysql = require('mysql');
let connection;
let cnt = 0;
export const cm_dbconnect = async() => {
let result = false;
var dbInfo = {
host : '127.0.0.1',
user : '****',
password : '**********'
}
let db = mysql.createConnection(dbInfo);
const attemptConnection = async() => {
console.log('Attempting to connect to db')
db.connect(async function (err) {
if (err) {
cnt += 1;
console.log('Error connecting to database, try again in 1 sec...')
db.destroy()
if (cnt<5) {
console.log(cnt);
function settimeoutpromise() {
return new Promise((resolve, reject) => {
setTimeout(() => {
cm_dbconnect();
resolve("end")
}, 1000);
})}
await settimeoutpromise();
}
}
})
}
await attemptConnection()
module.exports = db;
result = true
return {result: result, errCode: "", errDetail: ""};
}
这段代码包含控制器。
export const Controller = async () => {
let connect = await cm_dbconnect();
let db = require('');
let sql = 'select *** from ***;';
db.query(sql, function (error, results, fields) {
console.log(results);
})
console.log("aaaa");
console.log(connect);
}
let test = Controller();
但是,在重试完成之前返回结果。我认为这就是等待/异步不起作用的原因。
Attempting to connect to db
aaaa
{ result: true, errCode: '', errDetail: '' }
Error connecting to database, try again in 1 sec...
1
undefined
Attempting to connect to db
Error connecting to database, try again in 1 sec...
2
Attempting to connect to db
Error connecting to database, try again in 1 sec...
3
Attempting to connect to db
Error connecting to database, try again in 1 sec...
4
Attempting to connect to db
Error connecting to database, try again in 1 sec...
如果 5 次连接失败,我想在重试后获得返回值。请告诉我解决方案。
解决方案
您可以更改创建连接的方式:
const mysql = require('mysql');
const cm_dbconnect = async() => {
var dbInfo = {
host : '127.0.0.1',
user : '****',
password : '**********'
}
let db = mysql.createConnection(dbInfo);
try
{
await new Promise((resolve, reject) => {
db.connect(err => {
return err ? reject(err) : resolve({status: 'OK', message: 'Connected to DB'})
})
})
}
catch(err)
{
...handle errors...
}
module.exports = cm_dbconnect;
在您的控制器中:
const cm_dbconnect = require('path')
export const Controller = async () => {
let connect = await cm_dbconnect();
let count;
// already called once
while( connect.err && count < 4) {
count++;
connect = await cm_dbconnect();
}
if( connect.err && count >=4) return 'DB not connected at the moment'
console.log(`Connected with DB after this many tries`);
let db = require('');
let sql = 'select *** from ***;';
db.query(sql, function (error, results, fields) {
console.log(results);
})
console.log("aaaa");
console.log(connect);
}
let test = Controller();
我已经更改了数据库连接以根据连接获得承诺,在控制器中我们正在检查返回的内容。
您也可以查看此线程,它也有解决问题的好方法。
推荐阅读
- python - prepopulated_fields 导入数据库时不会触发
- php - 使用 laravel 使用 ajax 调用请求未定义
- javascript - 烧瓶 api 和 javascript 的 CORS 问题
- python - 数据框应用方法未更新所有行
- java - 发现无效的 Gradle JDK 配置。在 Android Studio 中打开 Gradle 设置更改 JDK 位置而 JDK 在任何地方都找不到
- java - 在 Glassfish-Netbeans 中找不到 Java 资源文件
- powershell - 如何以非管理员用户身份运行“Get-CimInstance”(windows server 2019,powershell 5.1)
- javascript - Reactjs-如何将数据或变量从一个组件传递到另一个组件
- accessibility - 使屏幕阅读器可以访问使用 react-virtualized Grid privative 制作的表格
- reactjs - React useMemo:如何全局缓存对象(不是每个钩子使用)