I'm currently dealing with the following script:
const db = require('../db')
const User = require('../models/user')
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
const main = async () => {
const users = [
new User({ name: 'Benny', age: 28, status: 'active' }),
new User({ name: 'Claire', age: 28, status: 'active' })
]
const newUsers = async () => {
await users.forEach(async user => await user.save())
}
await newUsers()
console.log("Created users!")
}
const run = async () => {
await main()
process.exit(0)
}
run()
The issue I'm facing is that process.exit()
seems to be running before main()
completes its execution, resulting in no users being created.
If I remove process.exit()
, the script runs successfully but hangs indefinitely.
So, how can I ensure that my script both executes properly and exits after completion?