循环以在Node.js Sequelize中获取异步数据

八足动物

我正在使用nodejs和sequelize框架,但是在尝试检索一些数据时遇到了问题

getAllMedicamentsWithTotal: function () {
    return medicamentService.getAll().then(function success(medicaments) {
        for(var i = 0 ; i < medicaments.length; i++){
            getTotalMedicament(medicaments[i]).then(function (total) {
                medicaments[i].dataValues.total = total;
            })
        }
    }, function fail() {

    })
}

我有这个功能,可以将所有药物连同库存一起获得。但是外部诺言在回调执行之前结束。我知道循环promise存在错误,但是有比修复这段代码更好的方法吗?

为了提供更多背景信息,我有一个表库存,该表库存有一个表药的外键,并且在库存表中有一定数量的药物。我想得到类似[{name1,sum(stockQuantity1)},{name2,sum(stockQuantity2)},...]的信息,但我无法做到这一点。

我将不胜感激任何帮助

丹尼尔·利兹克(Daniel Lizik)

你必须把一切都包裹在这样的承诺中

getAllMedicamentsWithTotal: function () {
  return new Promise((resolve, reject) => {

    // call your service first
    medicamentService
      .getAll()

      // with your array of results we need to map out an array of promises
      // then feed that array into Promise.all() 
      .then(medicaments => Promise.all(medicaments.map(med => {
        return getTotalMedicament(med);
      }))

      // the result of Promise.all() is an array of results
      // reduce the totals to get your accumulated total and resolve it to the caller
      .then(arrayWithTotals => {
        let total = arrayWithTotals.reduce((acc, obj) => acc += obj.dataValues.total, 0);
        resolve(total);
      });
  });

// elsewhere...

getAllMedicamentsWithTotal().then(total => { /** your total */ });

顺便说一句,看起来您正在为最有可能通过join查询完成的事情做很多逻辑IIRC sequelize将此称为查询对象include属性。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章