简体   繁体   English

如何正确处理Node.JS中的延迟操作?

[英]How do I properly handle delayed operations in Node.JS?

I'm new to ASYNC programming so please bear with me. 我是ASYNC编程的新手,请耐心等待。 I have a call to a web service API that can be unpredictably slow. 我有一个对Web服务API的调用,该调用可能会异常缓慢。 On the front end, I can handle it with a "loading" lightbox or something. 在前端,我可以使用“正在加载”灯箱或其他东西来处理它。 However, on the backend, I have my request: 但是,在后端,我有我的要求:

var req = http.request( options, function(res) {
  res.on('data', function(chunk) {
    doStuff();
  } );

  res.on('end', function() {
    doMoreStuff(); // This can take a while to get to.
    return someInfo();
  } );
} );

req.end();

All of this is in a makeRequest module. 所有这些都在makeRequest模块中。 So should I pass my callback function into makeRequest and then have it run after the 'end' event? 因此,我应该将回调函数传递给makeRequest ,然后在'end'事件之后运行它吗? It seems like this can lead to a very long chained event structure. 看来这会导致很长的链接事件结构。

So any help on how to structure this would be greatly appreciated. 因此,任何有关如何构建此结构的帮助将不胜感激。

note : the above is mostly pseudocode so if there are syntax errors, please understand that it's pseudocode 注意 :以上内容大部分是伪代码,因此如果存在语法错误,请理解为伪代码

Yes, generally you would pass a callback into whatever function you have this in, and when 'end' is emitted, you should take the data that you collected in the request, and pass it to your callback. 是的,通常您会将回调传递到具有此函数的任何函数中,并且在发出“ end”时,应获取在请求中收集的数据,并将其传递给回调。

I realize it's pseudocode and you may know, I just want to say it anyways. 我意识到它是伪代码,您可能知道,无论如何我只想说一遍。 Remember that 'data' can be called more than once, and that 'return' in your end function won't do anything. 请记住,“数据”可以被多次调用,而最终函数中的“返回”将无济于事。

For an example of doing a request, you can look at my answer over here. 有关提出请求的示例,您可以在这里查看我的回答。 Why won't my ExpressJS properly execute a request command? 为什么我的ExpressJS无法正确执行请求命令?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM