It is a simple controller. Receive requests from users, do task and response to them. My goal is to make the response as soon as possible and do the task then so the user will not notice the lengthy waiting time.
Here is my code:
router.post("/some-task", (req, res, next) => {
res.send("ok!");
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5000); // lengthy task
});
When post to this controller, I need to wait 5000ms before getting the response, which is not I want. I have tried promise but don't work either. What is the correct way to do it?
Improve version for Evyatar Meged answer:
router.post("/some-task", (req, res, next) => {
res.send("ok!");
setTimeout(()=>{
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5000); // lengthy task
}, 0);
});
It is not about res.end
, just setTimeout
do the thing. But I don't recommend this since it will block the entire app for handling other requests. You may need to think to use child process
instead.
You can have a callback after res.end
that will execute as soon as the response was sent.
router.get('/', function(req, res, next) {
res.end('123', () => {
setTimeout(() => {console.log('456')}, 5000)
})
});
Notice you're browser will receive 123
and after 5 seconds your server will log 456
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With