In an express route, I want to log a user's access to a db without:
- waiting for it to finish before performing the task the user wants
- caring about whether the logging was successful or not
I was wondering if the code does this correctly or not.
This thread (Down-side on calling async function without await) posted the same question essentially but the response was to avoid making the function async. However since sequelize
's upsert
returns a promise, I'm not sure if I did that properly in the code below. Can anyone verify?
I also noticed that if you don't await a promise in a async function's try-catch block, any errors thrown inside the promise will be unhandled. Because of that I made sure logAccess
catches and handles any errors. Is this the right way to do things?
const { Router } = require('express');
const moment = require('moment-timezone');
const Sequelize = require('sequelize');
function timeout(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
const userTable = sequelize.define('user', {
user_id: {
type: Sequelize.UUID,
primaryKey: true,
},
last_login: {
type: 'TIMESTAMP',
},
});
const logAccess = (user) => userTable.upsert({
user_id: user.user_id,
last_login: moment().tz('Australia/Sydney').format('YYYY-MM-DD HH:mm:ss'),
}).catch(() => console.log('Logging access to db failed'));
const makeCandy = async (user) => {
await timeout(1000);
return 'chocolate';
}
router.get('/get_candy', async (req, res) => {
try {
const user = req.body.user;
// Log access without blocking thread
logAccess(user);
const candy = await makeCandy(user)
res.status(200).send({ candy })
} catch (e) {
console.log(e);
}
})