如何解决等待异步/等待结果返回,以便使用这些值呈现动态html
几天前,我发布了一个与此有关的问题,得到的建议似乎在一定程度上起作用,返回了我想要的结果,但是在最终渲染数据后,我遇到了上一期。如果您想参考原始文章,请参阅以下文章: Grab the value of a span element
我使用Fetch而不是旧的xmlHttp API重写了所有代码,因为上一篇文章中建议这样做。我还想将这些功能分解为其他功能以提高可读性。
您将看到fetch API正在调用另一个数据库(出于隐私原因,我不得不隐藏标题)并调用callFetch
函数。 callFetch
函数本质上采用data
对象,并通过Google的distanceMatrix API运行data
中的地址,以便比较用户的输入地址(重复次数与{{1 }}数组)到addresses
对象中的地址。在data
内,我得到了所有比较的结果,并将结果推到单独的数组中。
在getDistance
中,我从getSortedValues
中获取结果,并按里程对它们进行排序(这是我要在渲染数据中返回的内容中最重要的部分之一),然后传递将它们作为单独的对象(getDistance
,facility
,distance
,time
)到称为address
的数组。
最后,combined
进行合并,并使用来自每个合并对象值的值呈现html,并动态呈现到页面。
我更新了一些代码,并尝试澄清更多内容。 Buttons要求我添加模拟值,因为用户无法测试代码。我尝试了一下,但是它改变了我的代码的行为,使动态部分不再需要从另一个不再存在等待问题的来源中提取数据。
我认为我的主要问题在于renderTemplate
。当我按下“提交”按钮(我将控制台日志添加到每个函数以更好地了解函数触发的顺序)时,您将第一次看到所有事件(在图像中),sortValues返回一个空数组。数组第二次填充所有四个15个值的对象。因此,我相信,无论我将sortValues
添加到async
还是renderTemplate
并添加await
,sortValues
仍然会在第一次出现时返回一个空数组。我认为所有这一切的根源在于等待sortValues
填充到combined
内部。有人知道我该怎么做才能等待或让sortValues
首次被填充?{p>
combined
sortValues
解决方法
我找到了一种方法来做到这一点,尽管这种方法有点笨拙,俗气,而且可能不是最有效的方法。我在for loop
的末尾添加了一个三元运算符,用于检查i
的值是否等于数组中最后一个元素的索引值。如果是这样,请等待1秒钟(通过运行setTimeout函数)以运行DistanceMatrix调用,以便获得一些值,然后调用sortValues
函数。至少它有效。所有代码都是相同的,但这里是callFetch
函数,其中添加了三元运算符,并添加了setTimeout
函数。
callFetch = async dataObject => {
console.log("callFetch fired");
// Map through the data object and grab the facId and address of each location
const facId = dataObject.data.map(e => e["6"].value);
const addresses = dataObject.data.map(e => e["8"].value);
// Create Google Maps distance service instance
distanceService = new google.maps.DistanceMatrixService();
for (let i = 0; i < addresses.length; i++) {
// Add matrix settings object
distanceService.getDistanceMatrix({
origins: [inputVal.toString("")],destinations: [addresses[i]],travelMode: "DRIVING",unitSystem: google.maps.UnitSystem.IMPERIAL,durationInTraffic: true,avoidHighways: false,avoidTolls: false,},// Set response and error capture
(response,status) => {
if (status !== google.maps.DistanceMatrixStatus.OK) {
console.log("Error:",status);
const message = document.querySelector("#message");
message.innerHTML = `Error: ${status}. Please resubmit.`;
} else {
distanceResult = response.rows[0].elements[0].distance.text;
timeResult = response.rows[0].elements[0].duration.text;
// Convert distanceResult values to integers and push to distanceArray to later sort
intDistanceResult = parseInt(distanceResult.replace(/,/g,""));
// Push results to respective arrays to pass to combined object inside of sortValues function
facilityArray.push(facId[i]);
distanceArray.push(intDistanceResult);
timeArray.push(timeResult);
facAddress.push(addresses);
}
});
(i == addresses.length - 1 ? setTimeout(() => { sortValues() },1000) : null)
}
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。