0

I have tried different ways to send data in arrays but it shows null. I am sure this is because the response fires before the actual response return. Well, this is my guess! I may be wrong.. I want to know the best practice to do this?

My expected result in the payload:

data: {
allCountries: [{TotalCountries: 12}]
allStates: [{StateId: "15327", STR: "Form",…}, {StateId: "15326", STR: "Form",…},…]
AllCities: [,…]
AllCust: {Id: "1825",…}
}

Now, in nodejs controller, I have 4 functions

exports.getAllDetails = async (req, res) => {
  
  if (!req.query.clientId) {
    return res.status(406).send({
      success: false,
      message: "ID is required"
    })
  }

  let id = req.query['custId'];
  let allCountries= await getAllCountries(req, res, id)
  // let allStates= this.getStates(req, res, id);
  // let allCities= this.getAllCities(req, res, id);
  // let custDetails= this.getCustDetails(req, res, id);


  return res.send({
    success: true,
    data:
    [allCountries]
    [allStates],
    [AllCities],
    [AllCust]
  })
}

Now I have created separate functions for all. i.e.

async function getAllCountries(req, res, id) {

  let allCountries;

  allCountries= `SELECT query..`

  connection.query(allCountries, (err, result) => {

    if (result) {
      if (result.length > 0) {
        return result;
      } else {
        res.status(204).send({
          success: false,
          message: `No data found.`,
        });
      }
    }
  });
}

I am getting null array in result? Can anyone tell me the best way to do this?

Raj
  • 15
  • 8
  • Why not making your API return a single object containing all the arrays? E.g. `data: {allCountries, allStates, allCities, allCust}` – nbokmans May 23 '22 at 14:26
  • I want the response like I said. The front-end developer suggested this to me so I have to send data as I mentioned first in the payload... – Raj May 23 '22 at 14:40

2 Answers2

1

Because you're trying to return data from callback function :

async function getAllCountries(req, res, id) {

  let allCountries;

  allCountries= `SELECT query..`

  connection.query(allCountries, (err, result) => {

    if (result) {
      if (result.length > 0) {
        return result; // this won't work because it is inside callback function.
      } else {
        res.status(204).send({
          success: false,
          message: `No data found.`,
        });
      }
    }
  });
}

you need to return promise object :

async function getAllCountries(id) {

  let allCountries;

  allCountries= `SELECT query..`

  return new Promise((resolve) => {
    connection.query(allCountries, (err, result) => {

    if (result) {
      if (result.length > 0) {
        resolve(result);
      } else {
        resolve(null);
      }
    }
    });
  });
}

also where you're using this function :

  let allCountries= await getAllCountries(id);
  if (allCountries == null) {
      return res.status(204).send({
         success: false,
         message: `No data found.`,
      });
  }
Harsh Kanjariya
  • 503
  • 5
  • 11
1

I Will recommend you start using try/catch to handle errors instead of all your function passing the param req/res, whit this solution your code will be more readable.

function getAllCountries(req, res, id) {
  return new Promise((res, rej) => {
    let allCountries;
    allCountries = `SELECT query..`;
    connection.query(allCountries, (err, result) => {
      if (err) {
        rej(err);
      }

      if (result.length === 0) {
        rej({
          success: false,
          message: `No data found.`,
        });
      }
      res(result);
    });
  });
}

in your main function:

exports.getAllDetails = async (req, res) => {
  if (!req.query.clientId) {
    return res.status(406).send({
      success: false,
      message: 'ID is required',
    });
  }

  try {
    let id = req.query['custId'];
    let allCountries= await getAllCountries(id)
    ...
  
  
    return res.send({
      success: true,
      data: {
        allCountries, //as you want this as array wrap the allCountries as [allCountries]
        ...
      }
    })
  } catch (err) {
    return res.status(400).send(err);
  }
};
Martinez
  • 1,109
  • 1
  • 4
  • 13
  • Noted. I will start using try/catch for error handling as you said. I appreciate your help. By the way, I am using try/catch when parsing data only.. but from now on will use like you suggested. – Raj May 23 '22 at 14:54