Node.JS ExpressJS异步与同步 [英] Node.JS ExpressJS async vs sync

查看:49
本文介绍了Node.JS ExpressJS异步与同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

早上好stackoverflow

Good morning stackoverflow

我有这条路线:

app.get('/myaccount', messages.getMessages, function(req, res, next) {
  messages = '';

  res.render('myaccount', {
    messages: messages
  });

});

messages.getMessages通过通过超级代理调出另一台服务器并获取一些消息以将其带回到用户(在该message变量中)来做很多事情

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)

这里的问题是,有时... messages.getMessages可能需要2-3秒来检索所有消息,因此当我刷新页面时有时会看到消息...有时我不是很随意.

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.

我对node还是很陌生,但是我认为messages.getMessages是异步的,因此在我返回消息之前,页面可能已完全呈现,并且所有变量都传递给了jadejs.

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.

在继续渲染路由之前,我基本上应该如何要求路由等待直到获得messages.getMessages数据后?

How can I basically require the route to wait until I get messages.getMessages data before proceeding to render the route?

谢谢!

推荐答案

If取决于getMessages函数的结构.应该是这样的:

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);
}

需要注意的重要一点是,您的getMessages不应如下所示:

The important thing to notice is that your getMessages should NOT look like this:

getMessages = function(req, res, next) {
   superAgent(x);
   next(req, res);
}

因为在最后一个示例中,将在superAgent完成之前调用next().

because in this last example next() will be called before superAgent completes.

这篇关于Node.JS ExpressJS异步与同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆