0

I realize JavaScript callbacks have been explained over and over, but I don't seem to find a way to save values from an inner callback function.

request.get('http://google.com', function(error, response, body){
    var $ = cheerio.load(body);
    // Process HTML here
    // How do I save the result from processing with a callback
}

// Or
var parse = function(error, response, body){
    // Process HTML here
    // Assign result to a variable or pass a callback to this function
};
request.get('http://google.com', parse);

I have multiple urls to process and I'd like to have one object summarizing the information afterwards.

By saving I mean either assigning to a variable or saving to a file.

Iyed Ghedamsi
  • 11
  • 1
  • 4

1 Answers1

0

Remember that the callback will be called when the async operation completes (like a second thread), meaning that the code after request.get will have been already executed then and you can't use return to send values back.

The solution is to make all the process inside the callback or to have other functions. Instead of returning the value, just make and call next_function(the_return_value) (something like that).

Gabriel
  • 2,170
  • 1
  • 17
  • 20
  • Well, say I created another function that does the processing, and passed it as a callback, which I've done, how would I pass a callback to the outer callback function ? – Iyed Ghedamsi May 11 '16 at 23:53