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