使用回调Javascript在多个函数中获取多个数据

使用回调Javascript在多个函数中获取多个数据,javascript,node.js,express,asynchronous,callback,Javascript,Node.js,Express,Asynchronous,Callback,我想要多个具有回调的函数,这些函数将返回DB的数据。例如: getStates: function (callback) { try { dbExecution.executeQuery("SELECT * FROM Table", function (err) { console.log(err); }, function (rowCount, mor

我想要多个具有回调的函数,这些函数将返回DB的数据。例如:

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);
        }
    }
但这个函数只有一个,我有五个函数,它们做相同的事情,但得到不同的数据。“主要”功能:

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 });
    });
});

如何使用异步Javascript(州、城市、宗教等)调用5个函数而不嵌套函数?

更改每个
get*
方法以返回
Promise
(而不是使用回调),然后您可以使用
Promise.all
在那些
Promises
的数组中。当数组中的所有
承诺都已解决时,
Promise.all
将解决-然后,您可以
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);
    }
  )
})
然后,一旦所有函数都与上面的一样:

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
  });
});
放松你的工作。。。在node.js中安装模块并使用它。。。几天前,我正在做同样的事情从数据库中获取数据,需要等待它。。。异步真的很好