【问题标题】:Async Promises Inside For LoopFor 循环内部的异步承诺
【发布时间】:2017-10-22 06:07:23
【问题描述】:

如果里面的for循环为真,我想每次都得到一个路由。

它按预期显示if HIT ${j},然后getSinglePart(partPath) 触发,按预期显示log 1,然后它应该在log 1 之后立即将res 返回到getSinglePart(partPath).then(res)

但是getSinglePart().then((res)) 在 for 循环结束后立即显示所有路由!

为什么即使它返回一个承诺?以及如何解决这个问题?

提前致谢:)

function getSinglePart(partPath){
return new Promise((resolve, reject) => {
    console.log('log 1');
    let tempDirectionsService = new google.maps.DirectionsService;
    let tempElevationService = new google.maps.ElevationService;
    let tempDirectionsRenderer = new google.maps.DirectionsRenderer({draggable: true, map: store.getState().map});
    tempDirectionsService.route({
        origin: partPath[0],
        //waypoints: waypointsArray,
        destination: partPath[partPath.length-1],
        travelMode: 'WALKING',
        avoidTolls: true
    }, (res, status) => {
        resolve(res);
    });
});}

function getParts(response){
let distances = [];
let legs = response.routes[0].legs;

for(let i=0; i<legs.length; i++){
    let steps = legs[i].steps;
    let distanceCounter = 0;
    let partsCounter = 0;
    let startNextIndexes = [0];

    for(let j=0; j<steps.length; j++){
        distances.push(steps[j].distance.value);
        distanceCounter += steps[j].distance.value;

        if(distanceCounter > 100000 || j === steps.length-1){
            startNextIndexes.push(j+1);
            let partPath = [];
            distanceCounter = 0;

            console.log(`if HIT ${j}`);
            for(let k=startNextIndexes[partsCounter]; k<=j; k++){
                for(let l=0; l<steps[k].path.length; l++){
                    partPath.push(steps[k].path[l]);
                }
            }

            getSinglePart(partPath).then((res) => {
                console.log('then');
                console.log(res);
            });
        }
    }
}}

【问题讨论】:

  • 循环不等待承诺?
  • @Bergi 不,它过着自己的生活:D 我会尝试阅读下面评论中的链接;)
  • 您可能还想详细说明您要完成的工作。也许,您实际上不需要等待每次迭代完成,而可以简单地在循环外进行处理。
  • @Maksym 是的,我想我最终会按照你所说的去做。我什至更早地考虑过,但想以这种方式解决它。感谢您的帮助:)

标签: javascript asynchronous es6-promise


【解决方案1】:

所描述的行为似乎是正确的,因为您实际上是在调度一堆“tempDirectionsService.route”函数以异步处理,然后退出循环,然后等待“tempDirectionsService.route”完成(每个“ then' 被打印为每个 'tempDirectionsService.route' 完成,没有特定的顺序,可能在循环期间或可能在循环之后)。如果您的目标是等待当前计划的“tempDirectionsService.route”完成,然后再进行循环的下一次迭代 - 您将必须相应地重写您的循环。例如:

JavaScript ES6 promise for loop

Correct way to write loops for promise.

【讨论】:

    猜你喜欢
    • 2017-10-30
    • 1970-01-01
    • 2017-07-18
    • 2018-12-24
    • 1970-01-01
    • 2015-12-18
    • 1970-01-01
    • 2014-10-27
    • 1970-01-01
    相关资源
    最近更新 更多