【问题标题】:Getting multiple data in multiple functions with callbacks Javascript使用回调Javascript在多个函数中获取多个数据
【发布时间】:2019-03-19 07:16:11
【问题描述】:

我想要多个具有回调的函数,这些函数将返回 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 个函数?

【问题讨论】:

  • 简化您的工作...在 node.js 中安装async 模块并使用它...几天前我正在做同样的事情以从数据库获取数据并需要等待它。 .. async 真的很适合它

标签: javascript node.js express asynchronous callback


【解决方案1】:

更改每个get* 方法以返回Promise(而不是使用回调),然后您可以在这些Promises 的数组上使用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
  });
});

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 2011-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多