Node.JS ExpressJS async vs sync

混江龙づ霸主 提交于 2019-12-24 12:50:14

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!