node.js 學(xué)習(xí)筆記005:使用async控制并發(fā)訪問數(shù)量

asynceventproxy同樣都是控制并發(fā)的,eventproxy會(huì)同時(shí)發(fā)起所有請(qǐng)求,所以在上一篇博客中最后出現(xiàn)了503的錯(cuò)誤;使用async則可以很好地解決這個(gè)問題,使用async能夠控制并發(fā)線程的數(shù)量


一、async

二、使用async限制并發(fā)訪問數(shù)量

1. demo

首先來個(gè)預(yù)熱程序看看如何使用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);
});

運(yùn)行結(jié)果:

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方法參數(shù)的含義說明

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

collection : 一個(gè)數(shù)組
item : collection的一個(gè)元素
callback : 回調(diào)函數(shù),該回調(diào)函數(shù)比較特殊,理解起來也比較困難,在iteratee方法中一定要調(diào)用該回調(diào)函數(shù),一般來說會(huì)有三種常用的使用方法:

使用方法形式 意義
callback(null) 調(diào)用成功
callback(null,data) 調(diào)用成功,并且返回?cái)?shù)據(jù)data追加到results
callback(data) 調(diào)用失敗,不會(huì)再繼續(xù)循環(huán),直接到最后的callback

3.使用async限制并發(fā)訪問數(shù)量完整代碼

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);
    });
    //驗(yàn)證得到的所有文章鏈接集合
    output(arr);
    //接下來遍歷arr,解析每一個(gè)頁面中需要的信息
    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錯(cuò)誤就解決了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 229,001評(píng)論 6 537
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,786評(píng)論 3 423
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,986評(píng)論 0 381
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,204評(píng)論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,964評(píng)論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,354評(píng)論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,410評(píng)論 3 444
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,554評(píng)論 0 289
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,106評(píng)論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,918評(píng)論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 43,093評(píng)論 1 371
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,648評(píng)論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,342評(píng)論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,755評(píng)論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,009評(píng)論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 51,839評(píng)論 3 395
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 48,107評(píng)論 2 375

推薦閱讀更多精彩內(nèi)容