1

I want multiple functions that have callbacks and this functions will return data of DB. An example:

getStates: function (callback) {
        try {
            dbExecution.executeQuery("SELECT * FROM Table",
                function (err) {
                    console.log(err);
                }, function (rowCount, more, rows) {
                    if (rowCount > 0) {
                        callback(rows);
                    } else {
                        callback(null);
                    }
                });
        } catch (ex) {
            console.log(ex);
            callback(null);
        }
    }

But this function is only one, I have a five functions that do same but get diferent data. The "main" function:

router.get('/content', sessionChecker, function (req, res) {
    Module.getStates(function (data) {
        res.render('info-user', { states: data });
    });
    Module.getReligion(function (data) {
        res.render('info-user', { religions: data });
    });
});

How can I do to call the 5 functions with Asynchronous Javascript (States, City, Religion, etc.) without having nested the functions?

1
  • 1
    ease your work... install async module in node.js and use it ... few days before I was doing the same thing to obtain data from database and needed to wait for it... async is really good for it Commented Oct 14, 2018 at 20:54

1 Answer 1

2

Change each get* method to return a Promise (rather than using callbacks), and then you can use Promise.all on an array of those Promises. The Promise.all will resolves when all of the Promises in the array have resolved - then, you can res.render:

getStates: () => new Promise((resolve, reject) => {
  dbExecution.executeQuery("SELECT * FROM Table",
    reject,
    function(rowCount, more, rows) {
      // if rowCount is 0, do you want to reject?
      // if (rowCount === 0) reject();
      resolve(rows);
    }
  )
})

Then, once all the functions look like the above:

router.get('/content', sessionChecker, function (req, res) {
  Promise.all([
    Module.getStates(),
    Module.getReligion(),
  ]).then(([states, religions]) => {
    res.render('info-user', { states, religions });
  })
  .catch((err) => {
    // handle errors
  });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.