首页 > 解决方案 > 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 次连接失败,我想在重试后获得返回值。请告诉我解决方案。

标签: mysqlnode.jstypescriptnode-mysql

解决方案


您可以更改创建连接的方式:

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();

我已经更改了数据库连接以根据连接获得承诺,在控制器中我们正在检查返回的内容。

您也可以查看线程,它也有解决问题的好方法。


推荐阅读