问题
Good morning stackoverflow
I have this route:
app.get('/myaccount', messages.getMessages, function(req, res, next) {
messages = '';
res.render('myaccount', {
messages: messages
});
});
the messages.getMessages does a bunch of stuff by calling out to another server via superagent and getting some messages to bring back to the user (in that messages variable)
The problem here is that sometimes... messages.getMessages might take 2-3 seconds to retrieve all the messages so when I refresh the page sometimes I see the messages... sometimes I don't its very random.
I am rather new to node but I assume that messages.getMessages is async so that the page might be fully rendered and all variables passed to jadejs before I get my messages back.
How can I basically require the route to wait until I get messages.getMessages data before proceeding to render the route?
Thanks!
回答1:
If depends on how your getMessages function is structured. It should be something like this:
getMessages = function(req, res, next) {
// asuming superAgent is async, pass the next
// function to it to call it AFTER it has completed
superAgent(x, req, res, next);
}
superAgent = function(x, req, res, next) {
// do something
...
// call the callback
next(req, res);
}
The important thing to notice is that your getMessages should NOT look like this:
getMessages = function(req, res, next) {
superAgent(x);
next(req, res);
}
because in this last example next() will be called before superAgent completes.
来源:https://stackoverflow.com/questions/13975641/node-js-expressjs-async-vs-sync