Search code examples
javascriptnode.jsasynchronouspromisetimeout

How to try until resolve (Promise in JavaScript)



lately I have been facing a connection problem that makes the connection between my code and db unstable...

TimeOut Error


As you may have noticed, that create a connection request error, and I need a way to make my Promise keep trying until resolve.
My code:
var results = sqlQuery(sql)
function sqlQuery (sql) {
   return new Promise((resolve, reject) => {
      sql.query(/*query*/, function (error, results, fields) {
         if (error) {
            console.log(error)
            reject(error)
         }
         resolve(results)
      })
   })
}

IMPORTANT : The code above is inside a while() that change the /*query*/ in each loop


Solution

  • I don't have a way of testing this, but try something like this, using a recursive function:

    var results = sqlQuery(sql)
    function sqlQuery (sql) {
       return new Promise((resolve, reject) => {
          sql.query(/*query*/, function (error, results, fields) {
             if (error) {
                return sqlQuery(sql).then(res => resolve(res));
             }
             resolve(results)
          })
       })
    }
    

    Although I have to say that redoing it over and over again just isn't the best idea...