等待异步/等待结果返回,以便使用这些值呈现动态html

如何解决等待异步/等待结果返回,以便使用这些值呈现动态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中获取结果,并按里程对它们进行排序(这是我要在渲染数据中返回的内容中最重要的部分之一),然后传递将它们作为单独的对象(getDistancefacilitydistancetime)到称为address的数组。

最后,combined进行合并,并使用来自每个合并对象值的值呈现html,并动态呈现到页面。

我更新了一些代码,并尝试澄清更多内容。 Buttons要求我添加模拟值,因为用户无法测试代码。我尝试了一下,但是它改变了我的代码的行为,使动态部分不再需要从另一个不再存在等待问题的来源中提取数据。

我认为我的主要问题在于renderTemplate。当我按下“提交”按钮(我将控制台日志添加到每个函数以更好地了解函数触发的顺序)时,您将第一次看到所有事件(在图像中),sortValues返回一个空数组。数组第二次填充所有四个15个值的对象。因此,我相信,无论我将sortValues添加到async还是renderTemplate并添加awaitsortValues仍然会在第一次出现时返回一个空数组。我认为所有这一切的根源在于等待sortValues填充到combined内部。有人知道我该怎么做才能等待或让sortValues首次被填充?{p>

console log

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 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-