使用nodejsasynchronous和请求模块

我试图使用asynchronous和请求模块在一起,但我不明白如何通过callback。 我的代码是

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); }); 

我试图按顺序获取3个文件并连接结果。 我的头被困在我试过的callback和我能想到的不同的组合。 谷歌没有太大的帮助。

请求是asynchronous函数,它不返回任何东西,当它的工作完成后,它会callback。 从请求的例子 ,你应该做这样的事情:

 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 } }); 

在你的例子中, fetch函数将被调用三次,一次为数组中的每个文件名作为第一个parameter passing给async.map 。 第二个callback参数也会被传递到fetch ,但是这个callback是由asynchronous框架提供的,当你的fetch函数完成它的工作时,你必须调用它,并将结果作为第二个参数提供给callback函数。 当所有三个fetch调用都调用提供给它们的callback时,将调用您提供的作为async.map的第三个参数的callback。

请参阅https://github.com/caolan/async#map

因此,为了回答您在代码中的具体问题,您提供的callback函数在所有请求结束时作为callback执行。 如果你需要传递一个callback来fetch你会做这样的事情:

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