node.js – 使用nodejs async和请求模块

栏目: Node.js · 发布时间: 6年前

内容简介:翻译自:https://stackoverflow.com/questions/11062995/using-nodejs-async-and-request-module

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

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

请求是异步函数,它不会返回一些东西,当它的工作完成时,它会回调.从 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
    }
});

翻译自:https://stackoverflow.com/questions/11062995/using-nodejs-async-and-request-module


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

零成本实现Web性能测试

零成本实现Web性能测试

温素剑 / 电子工业出版社 / 2012-2 / 59.00元

《零成本实现Web性能测试:基于Apache JMeter》是一本关于Web性能测试的实战书籍,读者朋友们在认真阅读完《零成本实现Web性能测试:基于Apache JMeter》后,相信能够将所学知识应用到生产实践中。《零成本实现Web性能测试:基于Apache JMeter》首先介绍基础的性能测试理论,接着详细介绍如何使用JMeter完成各种类型的性能测试。实战章节中作者以测试某大型保险公司电话......一起来看看 《零成本实现Web性能测试》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具