I'm using node with express 4.0. I can't find anything on the internet (including the docs) about embedding asynchronous code in a route.
With a middleware it's quite simple:
app.use('/something', function (req, res, next)
{
doSomethingAsync(function(err, probablySomethingElse)
{
// probably some error checking
next();
});
});
The problem with routes is that there is no next callback, so how does express know when to move to the next job?
app.get('/something', function (req, res)
{
res.render('someTemplate');
// no next() here, but it still works
});
If I had to guess, I'd say that express moves to the next task right after the above function exits. But out of curiosity I've launched the following code...
app.get('/something', function (req, res, next)
{
console.log(next);
});
...and there actually is some next callback passed. So what's going on here? How does it work behind the scenes? And how can I put asynchronous code there?
Express will wait until you call res.render to close the socket. Which means that you can pass res.render into a callback that takes X secs to execute and everything will still work.
The next allows you to go to the next route that maps your value, you can find a very good explanation here: node.js Express next()
But under what you are asking here. The moment render() is called on the res object, then data will be sent and the socket closed.