node.js 学习笔记005:使用async控制并发访问数量

asynceventproxy同样都是控制并发的,eventproxy会同时发起所有请求,所以在上一篇博客中最后出现了503的错误;使用async则可以很好地解决这个问题,使用async能够控制并发线程的数量


一、async

二、使用async限制并发访问数量

1. demo

首先来个预热程序看看如何使用mapList方法:

var async=require("async");
var currentCount=0;
console.log("will create a url list size 10 !");
var urls=[];
for(var i=0;i<10;i++){
    urls.push('http://www.example.com/'+i+".html");
}
async.mapLimit(urls,2,function(url,callback){
    var delay=parseInt(500);
    currentCount++;
    console.log("currentCount is :"+currentCount+",current url is :"+url+",use time is :"+delay+" mm");
    setTimeout(function(){
        currentCount--;
        callback(null,url+' html content ');
    },delay);
},function(err,result){
    console.log("result:");
    console.log(result);
});

运行结果:

will create a url list size 10 !
currentCount is :1,current url is :http://www.example.com/0.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/1.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/2.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/3.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/4.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/5.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/6.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/7.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/8.html,use time is :500 mm
currentCount is :2,current url is :http://www.example.com/9.html,use time is :500 mm
result:
[ 'http://www.example.com/0.html html content ',
  'http://www.example.com/1.html html content ',
  'http://www.example.com/2.html html content ',
  'http://www.example.com/3.html html content ',
  'http://www.example.com/4.html html content ',
  'http://www.example.com/5.html html content ',
  'http://www.example.com/6.html html content ',
  'http://www.example.com/7.html html content ',
  'http://www.example.com/8.html html content ',
  'http://www.example.com/9.html html content ' ]

2.mapLimit方法参数的含义说明

mapLimit方法的完整定义:
mapLimit(collection,iteratee(item,callback),callback(err,results))

collection : 一个数组
item : collection的一个元素
callback : 回调函数,该回调函数比较特殊,理解起来也比较困难,在iteratee方法中一定要调用该回调函数,一般来说会有三种常用的使用方法:

使用方法形式 意义
callback(null) 调用成功
callback(null,data) 调用成功,并且返回数据data追加到results
callback(data) 调用失败,不会再继续循环,直接到最后的callback

3.使用async限制并发访问数量完整代码

var express=require("express");
var superagent=require("superagent");
var cheerio=require("cheerio");
var url=require("url");
var eventproxy=require("eventproxy");
var async=require("async");
var app=express();
var baseUrl='https://cnodejs.org/';
function output(arr){
    for(var i=0;i<arr.length;i++){
        console.log(arr[i]);
    }
}
superagent.get(baseUrl).end(function(err,resp){
    if(err){
        return console.error(err);
    }
    var arr=[];
    var $=cheerio.load(resp.text);
    $("#topic_list .topic_title").each(function(idx,element){
        $element=$(element);
        var _url=url.resolve(baseUrl,$element.attr("href"));
        arr.push(_url);
    });
    //验证得到的所有文章链接集合
    output(arr);
    //接下来遍历arr,解析每一个页面中需要的信息
    async.mapLimit(arr,3,function(url,callback){
        superagent.get(url).end(function(err,mes){
            if(err){
                console.log("get \""+url+"\" error !"+err);
                console.log("message info:"+JSON.stringify(mes));
            }
            console.log('fetch '+url+" succeful !");
            //console.log("mess info:"+JSON.stringify(mes));
            var $=cheerio.load(mes.text);
            var jsonData={
                title:$(".topic_full_title").text().trim(),
                href:url,
                firstcomment:$("#reply1 .markdown-text").text().trim()
            };
            console.log("aim data is :"+JSON.stringify(jsonData));
            callback(null,jsonData);
        });
    },function(error,results){
        console.log("result :");
        console.log(results);   
    });
});

这样上一篇博客中的503错误就解决了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 156,907评论 4 360
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 66,546评论 1 289
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 106,705评论 0 238
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,624评论 0 203
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 51,940评论 3 285
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,371评论 1 210
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,672评论 2 310
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,396评论 0 195
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,069评论 1 238
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,350评论 2 242
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,876评论 1 256
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,243评论 2 251
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,847评论 3 231
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,004评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,755评论 0 192
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,378评论 2 269
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,266评论 2 259

推荐阅读更多精彩内容