简体   繁体   English

使用Node.js异步和请求模块

[英]Using nodejs async and request module

I'm trying to use async and request module together but i don't understand how the callbacks get passed. 我试图一起使用异步和请求模块,但我不明白回调如何传递。 My code is 我的代码是

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'm trying to fetch 3 files in order and concatenate the results. 我正在尝试按顺序获取3个文件并连接结果。 My head is stuck in callbacks I tryed and the different combinations I could think of. 我的头陷入了我尝试过的回调以及可以想到的各种组合中。 Google wasn't much help. Google并没有太大帮助。

Request is asynchronous function, it does not return something, when its job is done, 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
    }
});

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 . 在您的示例中, fetch函数将被调用三次,对于作为第一个参数传递给async.map的数组中的每个文件名,将调用一次。 A second, callback parameter will also be passed into fetch , but that callback is provided by the async framework and you must call it when your fetch function has completed its work, providing its results to that callback as the second parameter. 第二个回调参数也将传递给fetch ,但该回调由async框架提供,您必须在fetch函数完成其工作时调用它,并将其结果作为第二个参数提供给该回调。 The callback you provide as the third parameter to async.map will be called when all three of the fetch calls have called the callback provided to them. 您提供的第三个参数回调async.map当所有三个将被称为fetch来电呼吁向他们提供的回调。

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

So to answer your specific question in the code, the callback function you provide is executed as a callback at then end of all requests. 因此,要在代码中回答您的特定问题,您提供的回调函数将在所有请求结束时作为回调执行。 If you need to pass a callback to fetch you'd do something like this: 如果您需要传递回调以进行fetch可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM