我的代码中有一个流程,我需要获取技术人员驾驶时间的列表。我使用 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
来完成此操作,但与我在网上找到的不同之处在于他们没有使用它在递归方法内部。如果有人有任何想法,那将对我有很大帮助。谢谢!
最佳答案
您可以使用 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
}
...
关于javascript - 使用 async/await 和 setTimeout 创建递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61191558/