使用Promise.all使用Sequelize更新数据库中的多个记录:
db.Diet.findAll({
where: {
id: dietIds
}
}).then((existingDiets) => {
existingDiets.forEach(function (aDiet, index) {
var updatedObj = diets.filter(function (obj) {
return (obj.id === aDiet.id);
})
if (updatedObj[0]) {
if (updatedObj[0].name != aDiet.name) {
aDiet.name = updatedObj[0].name
}
existingDiets[index] = aDiet
}
})
db.sequelize.transaction(function (t) {
var promises = []
for (var i = 0; i < existingDiets.length; i++) {
console.log("i " + i)
var newPromise = existingDiets[i].save().then((Diet) => {
console.log("new Prom Diet " + Diet)
}, {transaction: t});
promises.push(newPromise);
};
return Promise.all(promises).then(function(updatedDiets) {
console.log("updatedDiets " + updatedDiets)
});
}).then(function (results) {
console.log("results " + results)
}).catch(function (err) {
console.log("NO!!! " + err);
return next(err);
});
})
控制台:
Express listening on port 3000!
i 0
i 1
i 2
数据库中的对象确实已更新,但未返回,因此未在控制台中记录。无法弄清楚我做错了什么。