I made a file called test-for-each-loop.js
in NodeJS to attempt to save a record to a mongodb database via the mongoose db wrapper. It looks like this:
const load = async () => {
const content = [0,0,0,0,0];
await content.forEach(async item=>{
const job = new Job({data:item});
await job.save();
});
process.exit();
};
load();
I ran this command from terminal: node test-for-each-loop.js
. The result is nothing gets saved to database. I identified the problem to be await job.save()
doesn't execute. My co-worker fixed my code by changing it to this:
const load = async () => {
const content = [0,0,0,0,0];
await Promise.all(content.map(async item=>{
const job = new Job({data:item});
await job.save();
}));
process.exit();
};
load();
I thought that because I put an await
in front of the content.forEach()
, that it would wait for the foreach to complete execution before firing the process.exit()
. Can some one explain to me why the await content.forEach
doesn't actually wait?
I noticed that if I remove process.exit()
from my first script, then the await content.forEach
will actually wait. How come?