尝试批量处理 Google ElevationService 的请求(并在 Stack Overflow 上留下一系列问题),现在我转向了 Promise 对象,这对我来说是全新的。
假设我有一个循环运行 4 次,或者在另一种情况下运行 7 次,或者在另一种情况下运行 2 次;我将如何在该循环中实现 Promise 方法?目前,我的设置是尝试针对给定的 Google map DirectionsResponse 以 250 LatLng 的时间批量获取海拔数据。
var currentBatch = 0;
while(currentBatch < totalElevationBatches) {
getRouteElevationChartDataBatch(currentBatch, batchSize);
currentBatch++;
}
function getRouteElevationChartDataBatch(batch, batchSize) {
return new Promise(function(resolve, reject) {
var elevator = new google.maps.ElevationService();
var thisBatchPath = [];
for (var j = batch * batchSize; j < batch * batchSize + batchSize; j++) {
if (j < directions.routes[0].overview_path.length) {
thisBatchPath.push(directions.routes[0].overview_path[j]);
} else {
break;
}
}
elevator.getElevationAlongPath({
path: thisBatchPath,
samples: 256
}, function (elevations, status) {
if (status != google.maps.ElevationStatus.OK) {
reject(status);
}
routeElevations = routeElevations.concat(elevations);
});
});
}
但是这些调用仍然是异步执行的,因为它们没有与 .then()
方法链接。我如何链接可变数量的链并知道它何时完成?抱歉,如果这是一个完全愚蠢的问题;但在查阅文档后我没有得到它( here 和 here )
最佳答案
我认为使用超时不会提供有效的解决方案,一种简单的方法是将每个 promise 调用添加到单个 promise 链的“then”,例如:
let promise = Promise.resolve(), // initialize promise chain
someArray = [ ... ];
for(let i=0;i<someArray.length;i++)
promise = promise.then(() => someCall(someArray[i]))
所以你的代码可以修改为以下:(我最后添加了解析调用,就像 Jaromanda X 所说的那样)
var currentBatch = 0, promise = Promise.resolve();
while(currentBatch < totalElevationBatches) {
promise = addToChain(promise, currentBatch, batchSize);
currentBatch++;
}
promise.then(...) // write code inside then that would handle once all the batches are processed
function getRouteElevationChartDataBatch(batch, batchSize) {
return new Promise(function(resolve, reject) {
var elevator = new google.maps.ElevationService();
var thisBatchPath = [];
for (var j = batch * batchSize; j < batch * batchSize + batchSize; j++) {
if (j < directions.routes[0].overview_path.length) {
thisBatchPath.push(directions.routes[0].overview_path[j]);
} else {
break;
}
}
elevator.getElevationAlongPath({
path: thisBatchPath,
samples: 256
}, function (elevations, status) {
if (status != google.maps.ElevationStatus.OK) {
reject(status);
}
routeElevations = routeElevations.concat(elevations);
resolve();
});
});
}
function addToChain(chain, batch, batchSize){
return chain.then(function(){
return getRouteElevationChartDataBatch(batch, batchSize);
});
}
关于javascript - 在 for 循环中使用可变编号 "then"进行 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36246577/