最近写一个新页面,涉及到异步问题,为了获得异步过程中的数据,以下分享两种方法;
两种方法一句话总结:
方法一,Http请求后调用.then实现response的数据同步,然后根据resp接着处理;
方法二,使用ES6中的Promise语法糖,实现异步等待resp;
方法一的代码:
其中invokeJsonRpc(RDS_CONFIG.APOLLO_CMDB_ENDPOINT_V3, "query.aggregate", queryParams)会发生一次HTTP请求
$("#submitFlushAll").on("click",function () { let clusterId = $("#cluster-id").val(); const queryParams = { graph: `graph g { redisCluster: RedisCluster[ id = "${clusterId}" ];}`, fields: [["redisCluster.name", "redisCluster.id", "redisCluster.used_memory"]] }; invokeJsonRpc(RDS_CONFIG.APOLLO_CMDB_ENDPOINT_V3, "query.aggregate", queryParams).then(resp =>{ let usedMemory = resp.result.children[0].data["redisCluster.used_memory"]; let clusterName = $("#cluster-name").val(); let details = { usedMemory : usedMemory, clusterName : clusterName, }; let request = { title: `Redis清除${clusterName}的所有数据`, applicant: $("#username").val(), projectId: Number($("#project-id").val()), createTime: moment().format("YYYY-MM-DD HH:mm:ss"), resourceType: REDIS_JIGSAW_RESOURCE_TYPE, operationType: "redis_flush_all", resource: Number($("#resource-id").val()), sensitive: false, audit: true, carbonCopy: null, details: JSON.stringify(details), extension: null }; submitJigsawWorkorder(request); });
方法二的代码:
注意Promise容器的构造,以及点击事件的处理函数为异步;
$("#submitFlushDatabase").on("click", async function () { let clusterId = $("#cluster-id").val(); let usedMemoryPromise = fetchUsedMemeory(clusterId); let usedMemory = await Promise.all([usedMemoryPromise]); let databaseNumber = $("#inputDatabaseNumber").val(); let clusterName = $("#cluster-name").val(); let details = { databaseNumber : databaseNumber, clusterName : clusterName, usedMemory : usedMemory, }; let request = { title: `Redis清除指定DB,指定DB:${databaseNumber}`, applicant: $("#username").val(), projectId: Number($("#project-id").val()), createTime: moment().format("YYYY-MM-DD HH:mm:ss"), resourceType: REDIS_JIGSAW_RESOURCE_TYPE, operationType: "redis_flush_database", resource: Number($("#resource-id").val()), sensitive: false, audit: true, carbonCopy: null, details: JSON.stringify(details), extension: null }; submitJigsawWorkorder(request); }); async function fetchUsedMemeory(clusterId) { const queryParams = { graph: `graph g { redisCluster: RedisCluster[ id = "${clusterId}" ];}`, fields: [["redisCluster.name", "redisCluster.id", "redisCluster.used_memory"]] }; let resp = await invokeJsonRpc(RDS_CONFIG.APOLLO_CMDB_ENDPOINT_V3, "query.aggregate", queryParams); let usedMemory = resp.result.children[0].data["redisCluster.used_memory"]; return usedMemory; }
两种方法的比较:使用Promise语法糖会使得代码结构性更加清晰,易读。
Promise学习可以参考这个链接:https://blog.csdn.net/major_zhang/article/details/79154287
原文地址:https://www.cnblogs.com/jayinnn/p/9957134.html
时间: 2024-10-13 15:35:22