I am very confused to why the the return resolve({ status: true, data: newIDs });
is called before the for
loop has finished.
Code
createPallet: (data) => {
return new Promise(async (resolve, reject) => {
const newIDs = [];
try {
for (const record of data) {
mysqlConnection.beginTransaction();
mysqlConnection.query(
"INSERT INTO ...",
[record.BatchId, record.PalletNumber, record.PrimaryWeightId],
async (error, results) => {
if (error) {
return reject(error);
}
// Create pallet sku record
await PalletSkusService.createPalletSku(
...
);
console.log(results.insertId);
newIDs.push(results.insertId);
}
);
}
return resolve({ status: true, data: newIDs });
} catch (error) {
mysqlConnection.rollback();
return reject(error);
}
});
},
Expectation
I expect the for loop to get all the new inserted id's and store them into newIDs
array. Once that is done, I can return a resolve with the data.
However, this part I don't quite understand is - why does the resolve is ran before the for loop has finished?
What is the correct approach in this situation?