简体   繁体   中英

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

I'm new to ASYNC programming so please bear with me. I have a call to a web service API that can be unpredictably slow. 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. So should I pass my callback function into makeRequest and then have it run after the 'end' event? 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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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