I'm curious about best practice here.
As I know the nature of Node (single process), I understand that responding to the web request won't end the process. So, assuming the return value is irrelevant (UPDATE), why do we need to wait for the promise(s) to finish before returning to the client?
In other words, here is a simple Express route:
router.post('/:perId/settings', auth.check, async (req, res) => {
try {
let per_id = req.params.perId;
let per_first_name = req.body.per_first_name.trim();
let per_last_name = req.body.per_last_name.trim();
let per_ea_address = req.body.per_ea_address.trim();
let per_tel_number = std.num_only(req.body.per_tel_number);
let promises = [];
let responses;
promises.push(db.f.stmt((`UPDATE PER SET PER_DATE_UPDATED = CURRENT_TIMESTAMP, PER_FIRST_NAME = @PER_FIRST_NAME, PER_LAST_NAME = @PER_LAST_NAME WHERE PER_ID = @PER_ID`), [
{var: 'PER_ID', type: sql.Int, val: per_id},
{var: 'PER_FIRST_NAME', type: sql.VarChar(25), val: per_first_name},
{var: 'PER_LAST_NAME', type: sql.VarChar(25), val: per_last_name}]));
promises.push(db.f.stmt((`UPDATE EA SET EA_DATE_UPDATED = CURRENT_TIMESTAMP, EA_ADDRESS = @EA_ADDRESS WHERE PER_ID = @PER_ID`), [
{var: 'PER_ID', type: sql.Int, val: per_id},
{var: 'EA_ADDRESS', type: sql.VarChar(60), val: per_ea_address}]));
promises.push(db.f.stmt((`UPDATE TEL SET TEL_DATE_UPDATED = CURRENT_TIMESTAMP, TEL_NUMBER = @TEL_NUMBER WHERE PER_ID = @PER_ID`), [
{var: 'PER_ID', type: sql.Int, val: per_id},
{var: 'TEL_NUMBER', type: sql.VarChar(10), val: per_tel_number}]));
promises.push(per.insert_history(per_id, (`Settings updated.`), req.user.PER_ID));
responses = await Promise.all(promises); promises = []; // is this necessary?
res.status(200).send(column_value);
} catch (err) {
await std.log('Unknown error caught', req.originalUrl, err);
res.status(500).send(('Unknown error caught in ' + req.originalUrl));
}
});
Is it necessary to include the line:
responses = await Promise.all(promises);
The process doesn't exit so the promises will continue to run, right? In my testing experiences, as expected, they do continue to run after response to the web request. But, I feel like I'm cheating.
Obviously, I'm simply trying to return to the web request as fast as possible.
As an aside, in the event of failure, my db.f.stmt() function will queue failed statements and auto-retry them after a few seconds. If they continue to fail, they are emailed to me so I can fix them and run them manually.
This is important b/c the queries above can only fail do to system issue as opposed to user error. So, returning w/ an error maybe isn't the best move.