我正在使用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 在回调执行之前结束。我知道循环 Promise 存在错误,但是有没有比修复这段代码更好的方法?
为了提供更多背景信息,我有一个库存表,该表具有表药物的外键,库存表中有药物的数量。我想要得到类似 [{name1, sum(stockQuantity1)}, {name2, sum(stockQuantity2)}, ...] 的东西,但我无法做到这一点。
如果有任何帮助,我将不胜感激
最佳答案
你必须将所有内容都包含在这样的 promise 中
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
property on your query object.
关于javascript - Nodejs Sequelize中循环获取异步数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37418290/