2

I'm using Node.js and npm mysql. How can I 'get rid' of return new Promise here and replace it with async await syntax?

const config = require('config');
const mysql = require('mysql');

class DatabaseConnection {

static connect(logger) {
    return new Promise(((resolve, reject) => {

        const con = mysql.createConnection({
            host: config.db.host,
            user: config.db.user,
            password: config.db.password,
            database: config.db.db,
        });

        con.connect((err) => {
            if (err) {
                reject(err);
            }
            else {
                logger.debug('Connected!');
                resolve(con);
            }
        });
    }));
  }

}


module.exports = DatabaseConnection;
Dave Chambers
  • 2,483
  • 2
  • 32
  • 55
  • 3
    await is to remove the .then() from a promise, but you still have to use and return a promise – juvian Mar 06 '18 at 20:47
  • 2
    You may want to switch over to using https://github.com/lukeb-uk/node-promise-mysql if possible (it wraps the `mysql` module) – Explosion Pills Mar 06 '18 at 20:49
  • 1
    async/await doesn't belong in that code section, but the code that consumes this can now use async/wait thanks to it returning a promise. – Kevin B Mar 06 '18 at 20:55

3 Answers3

0

Since .connect uses a callback function, not a Promise, you can't. There are several strategies for wrapping callbacks.

Daniel A. White
  • 187,200
  • 47
  • 362
  • 445
-1

Just use util.promisify to turn the API into a promise, then you can await it:

const { promisify } = require("util");

function connect(){

    const con = mysql.createConnection({
        host: config.db.host,
        user: config.db.user,
        password: config.db.password,
        database: config.db.db,
    });

    return promisify(con.connect.bind(con))();
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
-1

You can use this way. Refer to MDN link for async await.

const config = require('config');
const mysql = require('mysql');

class DatabaseConnection {
static connect(logger) {
  
  function getConnect() {
   return new Promise(((resolve, reject) => {
   const con = mysql.createConnection({
              host: config.db.host,
              user: config.db.user,
              password: config.db.password,
              database: config.db.db,
          });
  }
  async function asyncCall(){
            try
              {
              var status =  await getConnect();

              }catch(err){
              reject('failed');
              }
      }
  
  asyncCall();
}
module.exports = DatabaseConnection;
RobC
  • 22,977
  • 20
  • 73
  • 80
Mani Vel
  • 1
  • 1