【问题标题】:Pushing to an array not working in callback推送到在回调中不起作用的数组
【发布时间】:2021-10-02 17:55:18
【问题描述】:

查看代码中的 cmets 以了解实际发生/未发生的情况。基本上在函数中,array.push() 方法似乎不起作用,我无法理解为什么。任何帮助将不胜感激。

 var locationArray = new Array;

        request(process.env.RESOURCE_SHEET, (error, response, html) => {
            if(!error && response.statusCode == 200) {

                const $ = cheerio.load(html);
                
                $("h3").each((i, lle) => {
                    const location = $(lle).text();
                    if(location.includes("Kansas")) return;
                    if(location.includes("In Stock")) {
                        var level = location + " ✅";
                    } else {
                        var level = location + " ❌";
                    }
                    locationArray.push(level); // This doesn't push to the array
                });
            } 
        });
        locationArray.push("test") // This pushes to the array

        console.log(locationArray) // Output: "test"

【问题讨论】:

  • request 异步工作,您应该尝试在请求回调中控制数组。
  • 天啊!!!非常感谢,就是这样。
  • @HarshSaini 您将如何访问request 之外的数组?

标签: javascript arrays callback


【解决方案1】:

感谢 Harsh Saini。

他的回复:request 异步工作,您应该尝试在请求回调中控制数组。

工作代码:

var locationArray = new Array;

request(process.env.RESOURCE_SHEET, (error, response, html) => {
    if(!error && response.statusCode == 200) {

        const $ = cheerio.load(html);
            
        $("h3").each((i, lle) => {
            const location = $(lle).text();

            if(location.includes("Kansas")) return;
            if(location.includes("In Stock")) {
                var level = location + " ✅";
            } else {
                var level = location + " ❌";
            }
            locationArray.push(level);
        });
    } 
    console.log(locationArray)
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 2018-08-11
    • 2018-03-11
    • 2014-01-06
    相关资源
    最近更新 更多