iloq leo
iloq leo

Reputation: 21

Use async with NodeJs MySQL driver

I want to reform the function router.get('/', etc) to one that uses async and await. The res.send and connection.query are making the trouble I don't know how to handle them using async/await constructs.

I tried to use this function:

const awaitHandlerFactory = (middleware) => {
    return async (req, res, next) => {
        try {
            await middleware(req, res, next)
        } catch (err) {
            next(err)
        }
    }
};

This is the code that i have in the file:

var express = require('express');
// const data = require("../data/repo");
var router = express.Router();

let mysql = require("mysql");
let config = require('../config/config.json');

let connection = mysql.createConnection(config);
connection.connect();
//
let guests = {};
let query1 = "select * from guests";
//GET home page.
 router.get('/', function(req, res, next) {
     connection.query(query1,  function (err, rows) {
         guests['guests'] = rows;
         res.send(guests)
     });
 });

this function works the router.get('/', etc...)

I get this: and this is what i want.

 "guests": [
        {
            "event_id": 1,
            "guest_id": 1,
            "firstName": "lkasjdl;skj",
            "lastName": "lskajdfal;skdj",
            "role": "lsakdjfalskdjflks;adjf",
            "created_at": null,
            "updated_at": null
        },

Upvotes: 2

Views: 424

Answers (1)

ChiralMichael
ChiralMichael

Reputation: 1224

You need to convert the callback-style connection.query to something that can be awaited. promisify from util will do just that.

const express = require('express');
// const data = require("../data/repo");
const router = express.Router();

const util = require("util");
const mysql = require("mysql");
const config = require('../config/config.json');

const connection = mysql.createConnection(config);
const query = util.promisify(connection.query.bind(connection));
connection.connect();

const guests = {};
const query1 = "select * from guests";
//GET home page.
 router.get('/', async function(req, res, next) {
    try {
        const rows = await query(query1);
    } catch(ex) {
      //process your error
    }
    guests['guests'] = rows;
    res.send(guests);
 });

Upvotes: 1

Related Questions