【问题标题】:Creating a recursive function with async / await with setTimeout使用 setTimeout 使用 async / await 创建递归函数
【发布时间】:2020-07-26 05:29:14
【问题描述】:

我的代码中有一个流程,我需要在其中获取技术人员驾驶时间的列表。我使用Google Maps API 来获取起点和终点之间的行驶时间。众所周知,API 需要大约 1 秒或更长的超时时间才能正常工作而不会产生错误。我创建了一个递归函数来检索我需要在方法中使用 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 显然不会停止执行我的其余代码,因此返回技术人员数组只会返回空驱动时间的数组。 超时完成后,我希望它在调用它的方法中返回数组,如下所示:

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 来完成此操作,但与我在网上找到的不同之处在于他们没有在递归中使用它方法。如果有人有任何想法,那将对我有很大帮助。谢谢!

【问题讨论】:

    标签: javascript async-await


    【解决方案1】:

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

    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
        }
    
      ...
    

    【讨论】:

    • 我得试试这个。这实际上会等到该回调被调用后再执行它之后的代码吗?
    • 这可行,但是否可以在执行其他代码之前await 回调,而不是将其全部放入该方法中?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2016-01-22
    • 1970-01-01
    • 2021-08-03
    相关资源
    最近更新 更多