使用Node.js的async和request模块

7

我正在尝试将async和request模块一起使用,但我不理解回调函数是如何传递的。我的代码如下:

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个文件并将结果连接在一起。 我被回调函数卡住了,尝试了我能想到的不同组合。 谷歌没有提供太多帮助。

2个回答

32

请求是异步函数,它不会返回任何东西。当它完成任务时,会回调(callback)。从request examples中可以看到,应该这样做:

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

1
代码运行良好,非常容易理解我做错了什么 :) 谢谢 - andrei
您提供的示例链接没有显示任何回调函数,它们只是将日志记录到控制台。 - Catfish

3
在您的例子中,fetch函数将被调用三次,每次都针对作为第一个参数传递给 async.map 的文件名数组中的一个文件名。还会传入第二个回调参数到 fetch 函数中,但该回调是由 async 框架提供的,当您的 fetch 函数完成工作时,必须调用它,并将其结果作为第二个参数提供给该回调。在所有三个 fetch 调用都已调用它们提供的回调之后,将调用您作为第三个参数提供给 async.map 的回调。
请参见: https://github.com/caolan/async#map 因此,回答您代码中的具体问题,您提供的回调函数将作为所有请求结束时的回调执行。如果您需要向 fetch 传递回调,您可以像这样操作:
async.map([['file1', 'file2', 'file3'], function(value, callback) {
    fetch(value, <your result processing callback goes here>);
}, ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接