I'm a bit confused on how to make my nodejs exit after it completes. I know what the syntax is to exit the nodejs script. But I'm having a hard time figuring out how this whole async syntax really works. So what I want to do is call process.exit() after my nodejs application has completed everything. Right now when I put it in certain places it exits the script before the script has completed.
Here is my code where I'm getting emails from the server and writing them to the database.
(async function () {
try {
let pool = await sql.connect(config)
//Query the database
let emails = await pool.request()
.query('select uid from email')
emails.forEach(function(email) {
const request = pool.request();
request.input('uid', sql.VarChar, email.id);
request.input('mail_address', sql.VarChar, email.mailAddress);
request.input('mail_address_display_name', sql.VarChar, mail.displayName);
request.input('subject', sql.VarChar, mail.subject);
request.input('body', sql.VarChar, mail.body);
request.input('sent_date', sql.DateTime, mail.sentDate);
request.input('created_by', sql.VarChar, mail.CreatedBy);
var saveEmail = async function() {
let result = await request.query('INSERT INTO email_copy(uid, mail_address, mail_address_display_name, subject, body, sent_date, created_by) OUTPUT INSERTED.Email_ID values (@uid, @mail_address, @mail_address_display_name, @subject, @body, @sent_date, @created_by)', (err, result) => {
var emailId = result.recordset[0].Email_ID;
return result;
})
}
var r = saveEmail();
});
}
} catch (err) {
console.log(err);
// ... error checks
}
})()
.then((result) =>{
process.exit()
});
;
.thenafter an async function, as it returns a Promise once completed. The predicate insidethenwill be executed only once this function is completed.rpromise?