javascript - 在 for 循环中使用可变编号 "then"进行 Promise

标签 javascript loops promise

尝试批量处理 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() 方法链接。我如何链接可变数量的链并知道它何时完成?抱歉,如果这是一个完全愚蠢的问题;但在查阅文档后我没有得到它( herehere )

最佳答案

我认为使用超时不会提供有效的解决方案,一种简单的方法是将每个 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/

相关文章:

javascript 函数链接,链成员无需相互了解

javascript - 在 JavaScript 构造函数中赋值 'this'

javascript - 自定义单选按钮 - 在 IE 中损坏

ruby 遍历数组并提取元素

javascript - 为什么回调比 promise 更多 "tightly coupled"?

promise - q.js : Is it possible to know if a promise has resolved/rejected or not

javascript - 如何使用 JavaScript 查找数组中最早的日期

javascript - 循环动画时,只有最后一个循环运行

java - Tapestry 循环遍历 tml 文件中的嵌套 map

javascript - 在 fetch.then 中调用另一个函数 - Javascript