node.js - 使用 nodejs 异步和请求模块

标签 node.js asynchronous httprequest async.js

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

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 个文件并连接结果。我的头脑陷入了我尝试过的回调和我能想到的不同组合中。 Google 帮不上什么忙。

最佳答案

Request 是异步函数,它不返回任何东西,当它的工作完成时,它会回调。来自 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
    }
});

关于node.js - 使用 nodejs 异步和请求模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11062995/

相关文章:

node.js - 让 Node 等待 mongoDB 启动

javascript - 使 Express 中的特定路由的优先级高于动态路由

javascript - 如何在 Jade 中选择一个选项?

c++ - 如何使用 boost::statecart 在固定数量的线程上多路复用多个异步状态机?

javascript - 如何在异步nodejs中完成所有过程并打印出消息?

ruby-on-rails - 使用 javascript 响应 HTML 请求?

ruby-on-rails - Rails 中用于多个请求的实例变量

javascript - 在单个快速处理程序中处理 multipart/formdata、application/json 和 text/plain?

python - 异步: terminating all tasks when one of them throws exception

c++ - 使用 GNU cgicc 处理多个 POST 附件