I have mutiple update promises with sequelize and execute them parallely by Promise.all
All I get as Result is this: [[1]]
Here is the Code:
const express = require('express');
const router = express.Router();
const PLZ = require('../models/index').PLZ;
const Zone = require('../models/index').Zone;
const multer = require('multer');
const path = require('path');
const XLSX = require('xlsx');
router.post('/add', function (req, res, next) {
let zone = {
name: req.body.name,
color: req.body.color
};
const plzs = req.body.plzs;
for (let i = 0; i < plzs.length; i++) {
if (plzs[i].plz.toString() === plzs[i].city && plzs[i].plz.toString() === plzs[i].district) {
plzs[i].city = null;
plzs[i].district = null;
}
delete plzs[i].checked;
}
Zone.create(zone).then((result_zone) => {
let update_operations = [];
let zone_plzs = [];
// associate with plzs and put PLZs to database
for (let i = 0; i < plzs.length; i++) {
plzs[i].zone_id = result_zone.dataValues.id;
zone_plzs.push(plzs[i]);
update_operations.push(PLZ.update({zone_id: plzs[i].zone_id}, {where: {id: plzs[i].id}}).then((result) => {
return result
}));
}
Promise.all(update_operations)/*.then((arrayOfArrays) => {
return [].concat.apply([], arrayOfArrays);
})*/.then((result) => {
res.send({status: true, data: {zone: result_zone, plzs: result}})
}).catch(function (err) {
return next(err);
});
}).catch(function (err) {
next(err)
});
});
Does anyone know whats wrong?
Edit: I inserted the whole route to give you more details.
Update function of sequelize returns a number of affected rows (first parameter of result array).
PLZ.update({zone_id: plzs[i].zone_id}, {where: {id: plzs[i].id}}).then((result) => {
return result
});
So the output of this will be [1]
, and then you push this into update_operations
, for Promise.All
Promise.All will return the array of results so [[1]]
, this is what you will get. So there is nothing wrong in that , you are getting what is right.
I think , what you want is returning the result , instead of affected rows , in that case you need to add returning: true
, like
PLZ.update(
{ zone_id: plzs[i].zone_id },
{
where: {id: plzs[i].id} ,
returning: true, // <--------- HERE
}
);
NOTE : There is no need of .then((result) => { return result }); in your code . it will work without that also