Sending multiple arrays from nodejs API in response

Advertisements

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?

>Solution :

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.`,
      });
  }

Leave a ReplyCancel reply