Using nodeyns async and the request module

I am trying to use the async and request module together, but I do not understand how callbacks are passed. My code

var fetch = function(file, cb) { return request(file, cb); }; async.map(['file1', 'file2', 'file3'], fetch, function(err, resp, body) { // is this function passed as an argument to _fetch_ // or is it excecuted as a callback at the end of all the request? // if so how do i pass a callback to the _fetch_ function if(!err) console.log(body); }); 

I am trying to get 3 files in order and combine the results. My head was stuck in the callbacks I tried and the different combinations that I could think of. Google did not help much.

+7
source share
2 answers

A request is an asynchronous function, it does not return anything, when its work is completed, it calls back. From request examples , you should do something like:

 var fetch = function(file,cb){ request.get(file, function(err,response,body){ if ( err){ cb(err); } else { cb(null, body); // First param indicates error, null=> no error } }); } async.map(["file1", "file2", "file3"], fetch, function(err, results){ if ( err){ // either file1, file2 or file3 has raised an error, so you should not use results and handle the error } else { // results[0] -> "file1" body // results[1] -> "file2" body // results[2] -> "file3" body } }); 
+32
source

In your example, the fetch function will be called three times, once for each of the file names in the array passed as the first parameter to async.map . The second callback parameter will also be passed to fetch , but this callback is provided by the async framework, and you should call it when your fetch function has completed its work, providing its results to this callback as the second parameter. The callback that you provide as the third parameter in async.map is called when all three fetch calls have called the callback provided to them.

See https://github.com/caolan/async#map

So, to answer your specific question in the code, the callback function that you provide is executed as a callback when all requests are completed. If you need to pass a fetch callback, you will do something like this:

 async.map([['file1', 'file2', 'file3'], function(value, callback) { fetch(value, <your result processing callback goes here>); }, ... 
+3
source

All Articles