繁体   English   中英

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

[英]Loop to get asynchronous data in nodejs 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)},...]的信息,但我无法做到这一点。

我将不胜感激任何帮助

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

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属性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM