For循环未完成

时间:2019-04-14 23:50:38

标签: javascript google-maps for-loop asynchronous promise

我写了一个函数,它将根据距离来组织地址。正常工作,直到我输入5个地址。之后,for循环将只运行2次,而不是预期的5次。我在做什么错了?

async function getNextStop() {
    const lis = document.querySelectorAll('.stop');
    const stops = Array.prototype.slice.call(lis);
    const stopItems = Array.prototype.slice.call(lis);
    lis.forEach((i) => {
      i.remove();
    });
    for (let stopsIndex = 0; stopsIndex < stops.length; stopsIndex++) {
      const distances = [];
      for (let i = 0; i < stopItems.length; i++) {
        let lastLi = document.querySelectorAll('li');
        lastLi = lastLi[lastLi.length - 1];
        const newDis = await getDistance(lastLi.querySelector('address').innerText,
          stopItems[i].querySelector('address').innerText)
          .then(response => response);
        distances.push(newDis);
      }
      const lowest = distances.indexOf(Math.min(...distances));
      ul.appendChild(stopItems[lowest]);
      stopItems.splice(lowest, 1);
      console.log(stopsIndex, stops.length, stops, stopItems);
    }
  }

1 个答案:

答案 0 :(得分:0)

  

注意:我不是很通情达理-我在OP的网站上找到了getDistance功能,他在聊天室中链接了该功能:p

     

但是我很想限制速率:p

首先...处理getDistance中的错误-否则诺言将永远挂起-因此,永远await编辑

function getDistance(thing1, thing2) {
    return new Promise((resolve) => {
        const request = {
            origin: thing1,
            destination: thing2,
            travelMode: 'DRIVING',
        };
        directionsService.route(request, (result, status) => {
            if (status === 'OK') {
                resolve(Number(result.routes[0].legs[0].distance.text.replace(/[^\d.-]/g, '')));
            } else {
                reject({result, status});
            }
        });
    });
}

第二个-正如您所确定的那样,每秒限制为10个请求,然后限制您的速率

async function getNextStop() {
    const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
    const lis = document.querySelectorAll('.stop');
    const stops = Array.prototype.slice.call(lis);
    const stopItems = Array.prototype.slice.call(lis);
    lis.forEach((i) => {
        i.remove();
    });
    for (let stopsIndex = 0; stopsIndex < stops.length; stopsIndex++) {
        const distances = [];
        for (let i = 0; i < stopItems.length; i++) {
            let lastLi = document.querySelectorAll('li');
            lastLi = lastLi[lastLi.length - 1];
            await delay(100); // 10 per second
            const newDis = await getDistance(lastLi.querySelector('address').innerText, stopItems[i].querySelector('address').innerText);
                // remove the next line, it is redundant
                //.then(response => response);
            distances.push(newDis);
        }
        const lowest = distances.indexOf(Math.min(...distances));
        ul.appendChild(stopItems[lowest]);
        stopItems.splice(lowest, 1);
        console.log(stopsIndex, stops.length, stops, stopItems);
    }
}

另外,您可能要处理getNextStop中的错误

        try {
            const newDis = await getDistance(lastLiAddress, stopItem.querySelector('address').innerText);
            distances.push(newDis);
        } catch(e) {
            console.error('getDistance failed');
            console.error(e);
            throw e;
        }

但是,如果调用getNextStop的代码具有try / catch来处理任何错误,则不必要