0

I am New To async/await coding in node js. I am trying to fetch data from mysql and then populate the result into an object. But i am not finding a way how to do it in controller.js file. My source code similar to this.

  1. My Router File
const express = require("express");
const controller = require("controller");
const router = express.Router();
router.route("/").get(controller.findAll);
  1. My Controller File
const model = require("model");
exports.findAll = async (req, res) => {
   
    const all = model.getAll((err, data) => {
        if (err) {
            res.status(500).send({
                message: err.message || "Some error occurred while retrieving data.",
            });
        }
        return data;
    });
    const user = model1.getUser((err, data) => {
        if (err) {
            res.status(500).send({
                message: err.message || "Some error occurred while retrieving user.",
            });
        }
        return data;
    });
    // somefunctionality(all, user);
    // res.send(result);
};
  1. My Model file
const con = require("./db");

// constructor
const Customers= function (customer) {
    this.id = customer.id;
    this.first_name = customer.first_name;
    this.last_name = customer.last_name;
    this.email = customer.email;
};
Customers.getAll = () => {
    const query = `SELECT * FROM doctors`;
    sql.query(query, (err, res) => {
      if (err) {
          console.log("error: ", err);
          result(null, err);
          return;
    }
    console.log("customers: ", res);
    result(null, res);
};

user model same as customer

Thanks for your help

shahadat3669
  • 75
  • 2
  • 6

1 Answers1

1

The first thing I would do is covert your Customers.getAll method to return a promise:

model file

Customers.getAll = () => {
  const query = `SELECT * FROM doctors`;
  return new Promise((res, rej) => {
    sql.query(query, (err, data) => {
      if (err) {
        console.log("error: ", err);
        rej(err);
        return;
      }
    console.log("customers: ", res);
    res(data);
  })
};

(Note that you'll probably have to do something similar to the getAll method for your User model)

Now, in the controller, you can use try/catch to handle any errors.

*controller file

exports.findAll = async (req, res) => {
  try {
    const all = await model.getAll();
    const users = await model1.getUser();
    const result = somefunctionality(all, user);
    res.send(result);
  } catch(err) {
    res.status(500).send({
      message: err.message || "Some error occurred while retrieving data.",
    });
  }
};
Nick
  • 16,066
  • 3
  • 16
  • 32
  • thanks Nick for your help. but i was trying to do like only useing async and await keyword. – shahadat3669 Jul 03 '21 at 19:22
  • So that depends a bit on whether the `sql` package has promises built-in. Otherwise, you're going to _have_ to convert any callbacks to Promises because async await _is_ just promises under the hood. – Nick Jul 03 '21 at 19:24