问题描述
没有1
const r = new Array();
for (i = 0; i < 5; i++) {
const vari = 'print';
r.push(vari);
}
console.log(r);
控制台日志是 [ 'print','print','print' ]
no2(使用cheerio进行抓取)
const sqft = new Array();
for (k = 0; k < links.length; k++) {
request(`${links[k]}`,(error,response,html) => {
const $ = cheerio.load(html);
const pr = $('div[class="df2 "]').first().text();
sqft.push(pr);
});
}
console.log(sqft);
在此之前请求推送链接。现在当我 console.log(sqft) 我得到 []
。如果我在 for 循环中使用 console.log 它会显示数据。是 no1 和 no2 之间的区别还是cheerio 有问题?
谢谢!
解决方法
这就是你可以用 axios 做的事情
const sqft = new Array();
for (k = 0; k < links.length; k++) {
const res = await axios
.get(`${links[k]}`)
.then((result) => {
// do youre logic
//
const $ = cheerio.load(html);
const pr = $('div[class="df2 "]').first().text();
sqft.push(pr);
})
.catch((err) => {
//handle error
console.log("error");
});
}
console.log(sqft);
async function doSomeThing() {
const sqft = new Array();
for (k = 0; k < links.length; k++) {
const res = await axios.get(`${links[k]}`);
// logic
// ....
//
sqft.push(pr);
}
console.log(sqft);
}