繁体   English   中英

使用 async/await 和 setTimeout 创建递归 function

[英]Creating a recursive function with async / await with setTimeout

我的代码中有一个过程,我需要在其中获取技术人员驾驶时间的列表。 我使用Google Maps API来获取起点和终点之间的行驶时间。 正如你们大多数人所知,API 需要大约 1 秒或更长时间的超时才能工作而不会产生错误。 我创建了一个递归 function 来检索我需要在方法中使用setTimeout的时间列表,如下所示:

function GetTechDriveTimes(info, destAddress) {
  let techs = this.state.Techs
    .filter(tech => tech.Address != "" && !tech.Notes.includes('Not'))
    .map(tech => {
      let techObj = {
        TechName: tech.FirstName + " " + tech.LastName,
        TechAddress: tech.Address + " " + tech.City + " " + tech.State + " " + tech.Zip,
        KioskID: info.ID.toUpperCase(),
        DriveTime: "",
      };
      return techObj
    });

  let temp = [...techs]; // create copy of techs array

  const directionsService = new google.maps.DirectionsService();
  recursion();
  let count = 0;

  function recursion() {
    const techAddress = temp.shift(); // saves first element and removes it from array
    directionsService.route({
      origin: techAddress.TechAddress,
      destination: destAddress,
      travelMode: 'DRIVING'
    }, function (res, status) {
      if (status == 'OK') {
        let time = res.routes[0].legs[0].duration.text;
        techs[count].DriveTime = time;
      } else {
        console.log(status);
      }
      if (temp.length) {  // if length of array still exists
        count++;
        setTimeout(recursion, 1000);
      } else {
        console.log('DONE');
      }
    });
  }

  return techs;
}

此方法完成后,它将返回一个数组,其中包含技术人员及其各自的行驶时间到该目的地。 这里的问题是,使用setTimeout显然不会停止执行我的代码的 rest,因此返回技术人员数组只会返回空驱动时间的数组。 超时完成后,我希望它在调用它的方法中返回数组,如下所示:

function OtherMethod() {
 // there is code above this to generate info and destAddress

 let arr = GetTechDriveTimes(info, destAddress);

 // other code to be executed after GetTechDriveTimes()
}

我在网上寻找过类似的东西,看起来我需要使用Promise来完成此操作,但与我在网上找到的不同之处在于他们没有在递归方法中使用它。 如果有人有任何想法,那将对我有很大帮助。 谢谢!

您可以使用承诺,但您也可以使用“在 GetTechDriveTimes 之后执行的其他代码”创建回调并将其发送到 function:

function OtherMethod() {
  // there is code above this to generate info and destAddress

  // instead of arr = GetTechDriveTimes, let arr be the parameter of the callback
  GetTechDriveTimes(info, destAddress, function(arr) {
    // other code to be executed after GetTechDriveTimes()
  });
}

function GetTechDriveTimes(info, destAddress, callback) {
  ...

    if (temp.length) {  // if length of array still exists
      ...
    } else {
      console.log('DONE');
      callback(techs); // send the result as the parameter
    }

  ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM