简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM