【问题标题】:Why is my interval returning different results based on pushing to an array?为什么我的区间会根据推送到数组返回不同的结果?
【发布时间】:2019-12-16 10:10:52
【问题描述】:

我发生了一件非常奇怪的行为。我有一个 csv 文件,我需要对其进行地理编码。它有 250 行。谷歌地理编码 api 每秒有一个速率限制,所以我不能只在每一行上写一个 for 循环。我选择使用间隔。 每一分之一秒我都会发送 api 请求,完成后结果应该写入一个新的 csv 文件。但是,无论我做什么,我都只会得到 247 个结果。

为了查看中断发生的位置,我设置了一个called 变量来查看我的地理编码函数被调用了多少次。它确实被调用了 250 次。然后我开始将called 变量更深地移动到函数回调中,看看它是否被点击了 250 次。奇怪的是它是,它不是。 如果我在错误检查后立即将called 的增加包括在内,则为 250,但如果我将其放在push 语句下方,则为 247。

let called = 0;
/*Handles geocoding via google api*/
function geoCode(obj){
    console.log(`${rows.length} items remaining`);
    processing += 1;
    try {
        googleMapsClient.geocode({
            address: `${obj.ST_ADDRESS} ${obj.CITY} ${obj.STATE} ${obj.ZIP_CODE} ${obj.COUNTRY}`
        }, function(err, response) {
            if (!err) {
                called +=1; <------------HERE IT'S 250
                processing -= 1;
                const result = obj;
                result.LATITUDE = response.json.results[0].geometry.location.lat;
                result.LONGITUDE = response.json.results[0].geometry.location.lng;
                results.push(result);
                called +=1; <-----------------HERE IT'S 247
                if(rows.length < 1 && processing === 0){
                    // begin writing to file
                    writeFile(results);
                    console.log('called', called);
                }
            }else{
                console.log(err);
            }
        });
    }catch (e) {
        console.log(e);
    }
}

/* Loop through results at sustained pace to prevent rate limiting */
function locationLoop(){
    interval = setInterval(()=>{
        if(rows.length > 0){
            geoCode(rows.shift());
        }else{
            clearInterval(interval);
        }
    }, 50);
}

【问题讨论】:

标签: javascript node.js google-maps


【解决方案1】:

我不确定这个答案是否正确。

检测到 250 和 247 之间的代码可能会引发错误。例如,如果 API 无法解析坐标并且 response.json.results 不包含任何项目。尝试访问response.json.results[0].geometry 会出现类似can't get geometry of undefined 的错误。

这个错误丢失了,因为它不在具有 try-catch 的事件中。

因此,对于 250 个结果中的 3 个,Google 无法解析坐标。

Promises 是处理异步代码和故障的好方法。

【讨论】:

  • 谢谢你,你是对的。地址中的 3 个在响应对象上返回了错误,并且没有上升到我的 catch 块。
猜你喜欢
  • 2021-06-02
  • 2017-06-12
  • 1970-01-01
  • 2020-11-20
  • 1970-01-01
  • 1970-01-01
  • 2012-07-28
  • 2013-03-10
  • 1970-01-01
相关资源
最近更新 更多