'How to do something after sending a response in Express.js?
I'm developing a web app, which user could post a thread, 2 steps for this: one is to save the thread to thread collection, one is to save the threadID to user collection.
However, after saving to the thread collection, I wanna send the response immediately without waiting for the other saving action to finish.
Is there any recommend solution for this by using the express.js or node itself without using the other task queue sort of libs?
Could I just trigger an event then send the response? Will the event listener continue to run regardless the request is already fulfilled?
Thanks
Solution 1:[1]
You can send the response after the creation of the thread and before user data update for threadID.
Below is pseudo code for the same:
var express = require('express');
var app = express();
app.post('/', function(req, res, next) {
threadCreationRequest(function(err, data) {
res.send(data);
userUpdateRequest();
});
}
Solution 2:[2]
Create the thread id before saving it to thread collection. You could use uuid or if you are using MongoDB you could create an ObjectId using mongoose (or find another way to create an unique Id).
const uuidV1 = require('uuid/v1');
...
function saveThread(req,res){
const threadId=uuidV1(); // -> 6c84fb90-12c4-11e1-840d-7b25c5ee775a
let thread=req.body;
thread.id=threadId;
saveThread();
//return response (res.status(200).json(newThreadObject))
saveThreadId();
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | SeongJaeSong |
Solution 2 | kkicoo7 |