In my project I am trying to create a few Invoices, update Packages and send emails inside of a Promise.all.
I am using nodejs, express and sequelize.
For example this is part of my code:
exports.createInvoices = async (req, res) => {
try {
// Other logic...
const lastInvoice = await Invoice.findOne({
order: [['createdAt', 'DESC']],
attributes: ['number'],
});
let number = lastInvoice.number + 1;
await Promise.all(_.map(pckByBox, async (pck) => {
const user = await User.findOne(...);
await sequelize.transaction(async (t) => {
// This is the important part
const invoice = await Invoice.create({
userId: user.id,
total: pck.reduce((acc, curr) => acc + curr.totalPrice, 0),
number,
isAffiliate: !!(user.affiliateCardNo || user.affiliateDate),
byId: by.id,
}, { transaction: t });
await Promise.all(pck.map(async (p) => {
await Packages.update(some data);
}));
const invoiceData = await Invoice.findOne(some query);
await sendEmail(email, data);
});
}));
} catch (e) {
console.log(e);
}
}
The functions create well the Invoices, update the Packages and send the emails. But if I create more than one invoice, it creates with the same number.
I tried to put:
number++;
Inside of the sequelize transaction, after the transaction.
Also the lastInvoice function inside of the Promise like the User.findOne, also inside of the transaction and everytime the number doesn't increment.
How can I increment the number?