1

I'm using the Request library. I have an array of URLs (var resources) that I want to populate with the text content of those URLs.

My code looks like this:

var resources = [<URL_1>, <URL_2>, <URL_3>, ...];
var resourcesText = resourceToText(resources);

function resourcesToText(resources) {
  var text = [];

  for (var i in resources) {
  request(resources[i], fetch);
  }

  function fetch(error, response, body) {
    if (!error) {
      text.push(body);
    } else {
      console.log('Sorry. I couldn\'t parse that resource. ' + error);
    }
  }

  return text;

};

The problem is that resourceToText() returns the array before fetch() has had time to populate it. Thus, resourcesText ends up being empty. I assume higher order functions are meant to deal with this kind of problem but I can't fathom a way to work the callback.

What's the best approach to this problem?

user3574603
  • 3,364
  • 3
  • 24
  • 59
  • 2
    possible duplicate of [How to return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – Grundy Jul 28 '15 at 10:51
  • use promise or callback. – zb' Jul 28 '15 at 10:51

1 Answers1

1

Make an asynchronous function out of resourcesToText by:

Using an additional callback:

function resourcesToText(resources, callback) {
  var text = [],
      requestCount = resources.length;

  for (var i in resources) {
    request(resources[i], fetch);
  }

  function fetch(error, response, body) {
    if (!error) {
      text.push(body);
    } else {
      console.log('Sorry. I couldn\'t parse that resource. ' + error);
    }
    requestCount--;
    if(requestCount <= 0){
      callback(text);
    }
  }
};

Call the callback with your result text after you you got all the results of your requests using a counter (requestCount).

Now the call to resourcesToTextlooks like:

resourcesToText(resources, function(text){
  ...
});

Using deferred/promises

Instead of using a callback, you could also implement the concept of deferred/promises. There are many libraries out there, such as q (https://github.com/kriskowal/q)

remolueoend
  • 71
  • 1
  • 5