[英]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.