Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express.js: Do background task after sending response to client

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?

like image 780
wdetac Avatar asked Mar 19 '18 08:03

wdetac


2 Answers

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.

like image 61
skitty jelly Avatar answered Sep 23 '22 17:09

skitty jelly


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.

like image 26
Evyatar Meged Avatar answered Sep 25 '22 17:09

Evyatar Meged