0

I want to update ans object inside the fetchAll() functions and then send it back after successful updation. But the response I get is '[]'.

 var ans = []
  Country.fetchAll(newdate,(err, data) => {
      if (err)
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving data."
        });
      else ans.push(data);
      
    });

  State.fetchAll(newdate2,(err, data) => {
      if (err)
        res.status(500).send({
          message:
            err.message || "Some error occurred while retrieving data."
        });
      else ans.push(data);
    });
  res.send({ status: 201, data: ans });

How do I update the ans array inside the functions?

  • 2
    Just an async problem. you're sending your result before the fetches have completed. – Wyck Aug 10 '21 at 18:43
  • @Bravo you can delete your comment. It happens all the time. Be glad the question was edited in response to your comment. You helped. :) – Wyck Aug 10 '21 at 18:46
  • Does this answer your question? [How can I wait for set of asynchronous callback functions?](https://stackoverflow.com/questions/10004112/how-can-i-wait-for-set-of-asynchronous-callback-functions) – Wyck Aug 10 '21 at 18:48

1 Answers1

0

You can convert callback to Promise and using async/await to control the flow. async/await is supported in Node.js 7.6

const getCountry = (date) =>
  new Promise((resolve, reject) => {
    Country.fetchAll(date, (err, data) => {
      if (err) {
        reject(
          new Error(err.message || "Some error occurred while retrieving data.")
        );
        return;
      }
      resolve(data);
    });
  });

const getState = (date) =>
  new Promise((resolve, reject) => {
    State.fetchAll(date, (err, data) => {
      if (err) {
        reject(
          new Error(err.message || "Some error occurred while retrieving data.")
        );
        return;
      }
      resolve(data);
    });
  });

const foo = async (res) => {
  try {
    const [country, state] = await Promise.all([
      getCountry(newdate),
      getState(newdate2),
    ]);
    const ans = [country, state];
    res.send({ status: 201, data: ans });
  } catch (err) {
    res.status(500).send({ message: err.message });
  }
};

Node.js v8 added util function to promisify the callback, the code can be simplified to

const util = require('util');

const foo = async (res) => {
  try {
    const getCountry = util.promisify(Country.fetchAll);
    const getState = util.promisify(State.fetchAll);
    
    const [country, state] = await Promise.all([
      getCountry(newdate),
      getState(newdate2),
    ]);
    const ans = [country, state];
    res.send({ status: 201, data: ans });
  } catch (err) {
    res.status(500).send({ message: err.message || "Some error occurred while retrieving data." });
  }
};
Zhao Hong
  • 151
  • 5