7

我正在尝试同时使用异步和请求模块,但我不明白回调是如何传递的。我的代码是

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 个文件并连接结果。我的头陷入了我尝试过的回调和我能想到的不同组合中。谷歌没有太大帮助。

4

2 回答 2

32

请求是异步函数,它不返回任何东西,当它的工作完成时,它会回调。从请求示例中,您应该执行以下操作:

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
    }
});
于 2012-06-16T12:36:09.933 回答
3

在您的示例中,该fetch函数将被调用三次,对于作为第一个参数传递给的数组中的每个文件名调用一次async.map。第二个回调参数也将传递给fetch,但该回调由异步框架提供,您必须在fetch函数完成其工作时调用它,并将其结果作为第二个参数提供给该回调。async.map当所有三个fetch调用都调用了提供给它们的回调时,将调用您作为第三个参数提供的回调。

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

因此,要在代码中回答您的具体问题,您提供的回调函数将在所有请求结束时作为回调执行。如果您需要将回调传递给fetch您,请执行以下操作:

async.map([['file1', 'file2', 'file3'], function(value, callback) {
    fetch(value, <your result processing callback goes here>);
}, ...
于 2012-06-16T12:39:17.550 回答