Reputation: 69
I have some code in my controller, inside it I have a forEach loop inside of which there is a function that returns a Promise. After the promise is resolved I can correctly log the array it returns. Problem is javascript doesn't wait for the forEach loop to finish even though the controller is not async, and I can't figure out why... I've watched plenty of videos and read the post but something is not clicking I guess... Thanks in advance
exports.submitInv = (req, res) => {
let status = {
validated: [],
repacked: []
};
// ...other code...
console.log("1");
status.validated.forEach(async invoice => {
// repackInvoice() returns a PROMISE
let temp = await repackInvoice(invoice);
console.log(temp);
console.log("2");
temp.forEach(inv => {
status.repacked.push(inv);
});
console.log("3");
});
console.log("4");
console.log(status.repacked);
};
The console should look like this: 1, [invoice], 2, 3, 4, [...all invoices], Instead i get: 1, 4, [], [invoice], 2, 3
Upvotes: 0
Views: 85
Reputation: 653
You could try this, if it works :
exports.submitInv = (req, res) => {
let status = {
validated: [],
repacked: []
};
// ...other code...
console.log("1");
status.validated.forEach(invoice => {
const promises = [repackInvoice(invoice)];
Promise.all(promises)
.then(temp => {
temp.forEach(inv => {
status.repacked.push(inv);
});
return status;
}).catch(err =>{
console.log(err);
throw new Error(err);
})
});
console.log("4");
console.log(status.repacked);
};
Upvotes: 2