wdetac
wdetac

Reputation: 2842

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?

Upvotes: 9

Views: 4361

Answers (2)

skitty jelly
skitty jelly

Reputation: 375

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.

Upvotes: 5

Evya
Evya

Reputation: 2375

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.

Upvotes: 1

Related Questions