I have following route on my express server:
router.post("/doHeavyTask", async function (req, res) {
const status = heavyTask(req)
logAction(HEAVY_TASK) // logAction is defined below
return res.status(status).send()
})
and the following log function that simply inserts a document to my mongoDB Database:
export function logAction(type: USER_LOG_TYPES){
const db = getAppDatabase()
const userLog: UserLog = {
logType: type
}
getAppDatabase().db.collection('UserLogs').insertOne(userLog).then((insertedDoc) => {
// ...
// handle success
return
}).catch((error) => {
// ...
// handle failure
return
})
}
Will calling an async function (in my case logAction) before ending a HTTP request cause any problems? Is there anything one should keep in mind?
Really depends on what your HEAVY TASK does. If it involves changing the user state a little, then after the time you complete res.send(), the user may have an alternate state.
E.x. if HEAVY TASK was to just add a log into the database, you can do that and tell the user it's being inserted by res.send(), and theoretically be fine.
But if TEAVY TASK wants to do something like changing username, then when you hit res.send(), the task will still be running and users for an instant still won't see their username changed.