我正在抓一个网站,我使用带有节点js的请求库,所以我得到了一个我遍历的url数组并对每个请求执行请求,问题是请求是异步的,我需要做一些事情只有在完成所有请求后,才能获得代码:
for (var i = 0; i < urls.length; i++) {
request(urls[i], function (err,resp,body) {
if (!err && resp.statusCode == 200) {
var $ = cheerio.load(body);
var string = $('.author .mini').text();
var regExp = /(\+971|00971|05)\d{1,12}/g;
if(string.match(regExp)) {mobilePhones.push(string.match(regExp)[0])}
}
});
}
所以当所有请求都完成后,我只想要console.log(mobilePhones);
答案 0 :(得分:0)
var count = urls.length;
for (var i = 0; i < urls.length; i++) {
request(urls[i], function (err,resp,body) {
if (!err && resp.statusCode == 200) {
var $ = cheerio.load(body);
var string = $('.author .mini').text();
var regExp = /(\+971|00971|05)\d{1,12}/g;
if(string.match(regExp)) {mobilePhones.push(string.match(regExp)[0])}
}
count--;
if (count === 0) doSomething() // all requests are done.
});
}
答案 1 :(得分:0)
var myFunc = function (err,resp,body) {
if (!err && resp.statusCode == 200) {
var $ = cheerio.load(body);
var string = $('.author .mini').text();
var regExp = /(\+971|00971|05)\d{1,12}/g;
if(string.match(regExp)) {mobilePhones.push(string.match(regExp)[0])}
};
var p1 = request(urls[0], myFunc);
var p2 = request(urls[1], myFunc);
// Do this for all of urls.length
Promise.all([p1, p2, p3, p4, p5]).then(() => {
console.log(mobilePhones);
});