简体   繁体   English

Express.js:向客户端发送响应后执行后台任务

[英]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. 发布到这个控制器时,我需要等待5000ms才能得到响应,这不是我想要的。 I have tried promise but don't work either. 我已经尝试过承诺,但也没有工作。 What is the correct way to do it? 这样做的正确方法是什么?

Improve version for Evyatar Meged answer: 改进Evyatar Meged版本的答案:

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. 它不是关于res.end ,只是setTimeout做的事情。 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. 您可能需要考虑使用child process

You can have a callback after res.end that will execute as soon as the response was sent. 您可以在res.end之后进行回调,该回调将在响应发送后res.end执行。

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 . 请注意,您的浏览器将收到123并且在5秒后您的服务器将记录456

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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