I am working on a project that involves updating the entire mongoDB collection everyday. I am making multiple asynchronous calls so I decide to use async/await and try/catch. My code looks like this:
const updateMongoData = async () => {
try {
const data = await getData(); //This is the new data that I am using to update Mongo docs
const countries = await GlobalData.find();
countries.forEach(async (row) => {
const res = await Global.updateOne(
{ country: row.country },
{
//Use data
lastUpdated: Date.now(),
}
);
});
} catch (err) {
console.log(err);
}
};
Everything works fine except if I make a syntax error e.g Dated.now()
instead of Date.now()
. This is will give my an error saying
(node:8248) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 368)
I tried inserting another try catch instead my forEach and moved the forEach inside and this seems to catch the syntax error. Why does this work? And what is the cleanest way to do this?
GlobalData.find()
.then(countries => {
countries.forEach(async (row) => {
try{
const res = await Global.updateOne(
{ country: row.country },
{
//Use data
lastUpdated: Date.now(),
}
);
}
catch(err){
console.log(err);
}
})
}).catch(err => console.log(err));