0

I have an expressjs post route that can take few minutes to finish. The problem is that after some time, the client will try to send a post again. How can I do to make sure the client waits for the response?

My route looks like this:

router.post("/merge", (req: Request, res: Response, next) => {
    var timer = setInterval(()=>{
        // Check something that can take few minutes here
        // Tell the client to wait!
        if(completed){
            clearInterval(timer);
            res.end('completed');
        }
        if("error"){
            res.status(500).send("error");
        }
    }, 5000);
})
Nate
  • 7,606
  • 23
  • 72
  • 124
  • Assuming the client is a browser Ajax call, you're dealing with a browser Ajax timeout: https://stackoverflow.com/questions/1192375/timeout-behavior-of-different-browsers and https://stackoverflow.com/questions/7297833/how-long-will-the-browser-wait-after-an-ajax-request and https://stackoverflow.com/questions/24526201/ajax-does-setting-timeout-always-override-the-browsers-timeout – jfriend00 Jul 10 '17 at 13:54
  • show a message, and disable post button until a response is received – Jordi Flores Jul 10 '17 at 13:55
  • @JordiFlores The problem is that the browser will automatically send a post! – Nate Jul 10 '17 at 13:57
  • You might be better with an async approach: return a [202](https://httpstatuses.com/202) with a job id, then provide an api for the client to poll until complete, at which time you return the result. – 0x1mason Jul 10 '17 at 13:57
  • @jfriend00 The question is how to avoid the timeout and tell the client that the server is still working on the post? – Nate Jul 10 '17 at 13:58
  • And those three references all discuss how to control the browser timeout on the Ajax call so the browser won't hang up on you. You can't tell the browser that you're still working on it via the current http connection. You either send a response or not. Perhaps a better design is to communicate the result back over a webSocket connection which is designed for long running info to be sent from the server. – jfriend00 Jul 10 '17 at 14:00
  • @0x1mason interesting but I don't know when the job will be completed...should I do with the client what I do with the server (check every 5 seconds if it's completed)? If there is no other solution, I'll take that as an answer...but I'd prefer an easier solution – Nate Jul 10 '17 at 14:00
  • @ncohen Yes, whatever you think is a reasonable polling interval. Here's a little more on async REST patterns: http://restcookbook.com/Resources/asynchroneous-operations/ – 0x1mason Jul 17 '17 at 12:59

0 Answers0