Convert Promise to async

I am trying to convert mySQL connection from promise to asycn await so far I have the following setup:

const mysql = require("mysql");

const pool = mysql.createPool({
  connectionLimit: 10,
  password: "",
  user: "root",
  database: "usersdb",
  host: "localhost",
  port: "3306",
});

let usersDB = {};

usersDB.all = () => {
  return new Promise((resolve, reject) => {
    pool.query("SELECT * FROM users", (err, results) => {
      if (err) {
        return reject(err);
      }

      return resolve(results);
    });
  });
};

usersDB.one = (id) => {
  return new Promise((resolve, reject) => {
    pool.query("SELECT * FROM users WHERE id = ?", [id], (err, results) => {
      if (err) {
        return reject(err);
      }

      return resolve(results[0]);
    });
  });
};

module.exports = usersDB;

Is there a way to convert this codes:

return new Promise((resolve, reject) => {
    pool.query("SELECT * FROM users", (err, results) => {
      if (err) {
        return reject(err);
      }

      return resolve(results);
    });

to async await and make the code more compress or succint?

UPDATE: on my router, I have these codes:

const router = express.Router();

router.get("/", async (req, res) => {
  try {
    let results = await db.all();
    res.json(results);
  } catch (error) {
    console.log(error);
    res.sendStatus(500);
  }
});

router.get("/:id", async (req, res) => {
  try {
    let results = await db.one(req.params.id);
    res.json(results);
  } catch (error) {
    console.log(error);
    res.sendStatus(500);
  }
});

So it just fine calling async await twice?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can convert any callback function to promise by using util.promisify

const util = require('util')
// ....
const query = util.promisify(pool.query)



// ... inside some async function
const users = await query("SELECT * FROM users;")


// or promise style
query("SELECT * FROM users;")
   .then((users) => {
      console.log(users)
    })
    .catch(console.error)

Method 2

usersDB.one = (id) => {
    try {
        const users = pool.query("SELECT * FROM users WHERE id = ?", [id]);
        return users;
    } catch (e) {
        throw e;
    }
};

Or more simply,

usersDB.one = (id) => pool.query("SELECT * FROM users WHERE id = ?", [id]);

Method 3

What you want to do is to promisify the DB call. You can acheive this by factorisation :


const mysql = require("mysql");

const pool = mysql.createPool({
  connectionLimit: 10,
  password: "",
  user: "root",
  database: "usersdb",
  host: "localhost",
  port: "3306",
});

function promisify(...args){
    return new Promise((resolve, reject) => {
        pool.query(...args, (err, result) => {
            if(err) reject(err);
            resolve(result);
        });
    });
}

let usersDB = {};

//Then you can call it this way : 

usersDB.all = async () => {
    return await promisify("SELECT * FROM users");
   //Note that you can avoid to await there.
};

usersDB.one = async (id) => {
    return await promisify("SELECT * FROM users WHERE id = ?", [id]);
};

module.exports = usersDB;


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x