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


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

查看所有标签

猜你喜欢:

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

设计冲刺

设计冲刺

[美] 杰克·纳普、[美] 约翰·泽拉茨基、[美] 布拉登·科维茨 / 魏瑞莉、涂岩珺 / 浙江大学出版社 / 2016-8 / 58.00元

Uber / Nest Lab / Medium / Gmail / Chrome 成功助推无数现象级产品的谷歌风投团队(Google Ventures)首次现身著述 雄踞《纽约时报》/《华尔街日报》/ 亚马逊书店三大畅销榜榜首 当选Inc.杂志2016年必读商业佳作 ------------------- ※内容简介※ 谷歌风投投资的公司每天都会面对各种至关重......一起来看看 《设计冲刺》 这本书的介绍吧!

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

HTML 编码/解码

SHA 加密
SHA 加密

SHA 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器