gpt4 book ai didi

javascript - window.setTimeout 用于处理异步调用同步?

转载 作者:行者123 更新时间:2023-12-03 07:20:40 25 4
gpt4 key购买 nike

我正在开发 Google map API 功能,其中包含获取路线结果中某个点的海拔高度。这对于较小的路线来说很好,但是具有更多路径的较大路线就会成为问题。因此,我将总路径分成单独的批处理来执行,但有时它们以随机顺序返回。这是因为 Google Elevation Service 是异步调用的(没有其他方法)。

期望的结果是在所有批处理完成后输出高程数据(即使只是一批)。所以我想合并 window.setTimeout 来按顺序处理调用,但我想知道两件事:

  1. 这是一个好方法,还是有更好的替代方案?
  2. 我不断地包装功能,但最终没有得到任何好处。也许有人可以指出我正确的方向?下面是我的伪方法。

    函数 getElevationData() { var 电梯 = new google.maps.ElevationService(); var 批量大小 = 250; var heightBatches = Math.ceil(directions.routes[0].overview_path/batchSize);

    for(var i = 0; i < heightBatches; i++) { var thisBatch = [];

    for(var = j = i * batchSize; j < i * batchSize + batchSize; j++) {
    if(j < directions.routes[0].overview_path.length) {
    thisBatch.push(directions.routes[0].overview_path[j]);
    } else {
    break;
    }
    }

    getElevationBatchData(elevator, i, batchData);

    }}

    函数 getElevationBatchData(电梯, 批处理, 数据) { window.setTimeout(函数() { //检查它是否已经完成..?如果没有,再次重新触发该函数?

    elevator.getElevationAlongPath({
    path: data,
    samples: 256
    }, function(elevations, status) {
    // process the result (basically checking for status OK, concatenating and adding rows to the DataTable
    }

    }, 100);}

对代码标记感到抱歉;当我在 SO 的编辑器中输入更多伪代码时,将不再应用正确的代码格式...

最佳答案

为什么不能并行运行所有请求(即使用 setTimeout 方法,但这里很可能甚至没有必要),然后在所有这些请求完成并返回部分结果时显示总体结果?

 function onRequestComplete(index, context) {
alreadyProcessed++;
if (alreadyProcessed == totalNumOfRequests) {
showResults();
}
batches[index].data = context;
}

function doAsyncRequest(index) {
someObject.doAsyncRequest(batches[index], function (err, data) {
onRequestComplete(index, data);
});
}

for(var i=0;i<totalNumOfRequests;i++){
doAsyncRequest(i);
};

关于javascript - window.setTimeout 用于处理异步调用同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36234597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com