Home > database >  Node.js, Express, run a function AFTER sending a redirect
Node.js, Express, run a function AFTER sending a redirect

Time:06-18

I have a simple express function.

app.post('/thing', ensureLoggedIn("/loginpage"), urlencodedParser, (req, res) => {
    var func = req.body.func
    res.redirect('/')
    longRunningCalculation()
})

I want to return, and then, do the longRunningCalculation (it takes, say, five seconds).

Surprisingly this just doesn't work. The web browser site there and waits for the five seconds, and then, reloads.

If I do this ...

app.post('/thing', ensureLoggedIn("/loginpage"), urlencodedParser, (req, res) => {
    var func = req.body.func
    res.redirect('/')
    setTimeout(longRunningCalculation, 1100)  // sloppy but WTF
})

It "works" but obviously is crap.

By "works" I mean, the web page DOES reload instantly; then 1.1 seconds later the long process starts and works as expected.

(Bizarrely if I do a small time, like say "100", it "does not" work; it will, again, behave so that the web page only reloads, once, the long calculation is done.)

What's the solution?

CodePudding user response:

It seems that calling next(); should help you. You can try to do following:

app.post('/thing', ensureLoggedIn("/loginpage"), urlencodedParser, (req, res) => {
    var func = req.body.func;
    res.redirect('/');
    next();
    longRunningCalculation();
})

And you can look towards this to do things in more right way:

process.nextTick(() => {
  // do something
});
  • Related