Javascript 阵列的控制台日志为空

Javascript 阵列的控制台日志为空,javascript,node.js,arrays,cheerio,Javascript,Node.js,Arrays,Cheerio,我有以下两个代码示例: 一号 在此之前,链接被推入请求。现在,当我使用console.log(sqft)时,我得到了[]。如果我在循环中输入console.log,它将显示数据。是1号和2号的区别还是cheerio在制造问题? 谢谢 看起来您有异步操作。因此,我们需要使用async和wait关键字使执行同步: async function yourFunction() { const sqft = new Array(); for (k = 0; k < links.len

我有以下两个代码示例:

一号

在此之前,链接被推入请求。现在,当我使用console.log(sqft)时,我得到了
[]
。如果我在循环中输入console.log,它将显示数据。是1号和2号的区别还是cheerio在制造问题?
谢谢

看起来您有异步操作。因此,我们需要使用
async
wait
关键字使执行同步:

async function yourFunction() {
    const sqft = new Array();
    for (k = 0; k < links.length; k++) {
        // here we are waiting for the promise to be resolved
        let res = await request();
        const $ = cheerio.load(res.html);
        const pr = $('div[class="df2  "]').first().text();
        sqft.push(pr);
    }
}
异步函数yourFunction(){ const sqft=新数组(); 对于(k=0;k这就是你如何使用axios的方法

const sqft=new Array();
对于(k=0;k{
//你有逻辑吗
//
const$=cheerio.load(html);
const pr=$('div[class=“df2”]”)。first().text();
平方英尺推力(pr);
})
.catch((错误)=>{
//处理错误
控制台日志(“错误”);
});
}
控制台日志(sqft);
异步函数doSomeThing(){
const sqft=新数组();
对于(k=0;k}
我认为请求函数是异步的,因此在调用请求之前会执行console.log。是否有办法等待该请求完成,然后继续执行代码@卢西亚夫·鲁尔德这能回答你的问题吗?此软件包已弃用。请使用axios。我将示例代码放在回答中。类似的操作不应该起作用:
const sqft=new Array();异步函数firstFunction(){for(k=0;k
${links[k]}
,(错误、响应、html)=>{const$=cheerio.load(html);const pr=$('div[class=“df2”]')。first().text();sqft.push(pr);}}异步函数secondfunction(){await firstFunction();console.log(sqft);}secondfunction()请看我的最新答案我是用cheerio和axios这样做的。但是在对象sqft的console.log未定义之后,我得到了一个错误@阿米尔
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);

async function yourFunction() {
    const sqft = new Array();
    for (k = 0; k < links.length; k++) {
        // here we are waiting for the promise to be resolved
        let res = await request();
        const $ = cheerio.load(res.html);
        const pr = $('div[class="df2  "]').first().text();
        sqft.push(pr);
    }
}