weijiyang / GOOD-IDEA

这里记录一些灵感~详见ISSUES
1 stars 0 forks source link

多个请求并发执行 异步顺序调用 #77

Open weijiyang opened 4 years ago

weijiyang commented 4 years ago

并非并发请求...


var request = require('request');

// 异步获取网络资源的方法 getWeb = (index, getCallback) => { var url = 'http://www.duzixi.com';

request(url, function (error, response, body) { 
    if (!error && response.statusCode == 200) 
    {    
        getCallback(body);
        return body;

    } else {
        console.log(response.statusCode + " " + error);
        getCallback("");
        return "";
    }
})

}

// 定义迭代方法 function action(i) { if (i == 10) { // 满足条件,结束迭代 console.log("All done!"); return; } else { getWeb(i, (body)=>{ console.log(i); action(i + 1); // 迭代调用 }) }
}

// 从0开始调用迭代方法 action(0);