I am trying to:
Everything works great, except that the last part of my code that is outside of the two loops runs before the async tasks finish.
My question is - how do I make sure that the last part of the code (console.log and the DB query that retrieves the newly-saved transactions) executes after all the async tasks finish?
I was trying to use callbacks / promises and follow other guides, but I did not manage to get it to work, so I would be grateful for some help!
I have the following Express.js code:
router.post("accounts/transactions", async (req, res) => {
//user id sent from frontend
const user_id = req.body.user_id;
//Find accounts by user_id in DB
const accounts = Account.find({ user_id: user_id }).then((accounts) => {
return accounts;
});
//Once accounts retrieved from DB, loop over them and fetch transactions for each account
(await accounts).forEach(async (account) => {
const url = `https://someExternalApi.whatever/${account.accountId}/transactions`;
const options = {
//fetch request options
};
const response = await fetch(url, options)
.then((res) => res.json())
.catch((e) => {
console.error({
message: "Error!",
error: e,
});
});
//Once transactions for a single account are retrieved from external API,
//loop over them and save them one-by-one to DB
(await response).transactions.booked.forEach(async (transaction) => {
const filter = {
transactionId:
transaction.transactionId
};
const mongooseOptions = { upsert: true, new: true };
const update = {
user_id: user_id,
//...other keys-value pairs for transaction record
updated: Date.now(),
};
//Save single transaction to DB
Transaction.findOneAndUpdate(filter, update, mongooseOptions)
.then(
console.log(
`Transaction ${
transaction.transactionId
} saved!`
)
)
.catch((error) => console.log(error));
});
});
//The problem is that the below runs before the above async operations are finished
console.log("All transactions updated!");
Transaction.find({ user_id: user_id }).then((transactions) => {
res.json(transactions);
});
});
Thanks!