1. 程式人生 > >jQuery中非同步問題:資料傳遞

jQuery中非同步問題:資料傳遞

最近寫一個新頁面,涉及到非同步問題,為了獲得非同步過程中的資料,以下分享兩種方法;

兩種方法一句話總結:

方法一,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