繁体   English   中英

如何使用从两次响应中获得的数据并在第三次获取中使用它?

[英]How to use data obtained from two response and use it in a third fetch?

我打了两个 API 端点来获取totalPolicetotalZone ,我希望在从第三个获取请求获得的第三个响应中使用这两个变量。

// First API to get totalPolice
fetch("url1").then(
    res=>{
        res.json().then(
            data=>{
                    totalPolice = data.length
            }
        )
    }
);
// Second API to get total Zones
fetch("url2").then(
    res=>{
        res.json().then(
            data=>{
                    totalZone = data.length
            }
        )
    }
);
// Third API that uses totalPolice and totalZone variable
fetch("url3").then(
    res=>{
        res.json().then(
            data=>{
                    data.length = totalPolice + totalZone // dummy equation
            }
        )
    }
);

我面临的问题是这些获取请求是异步发生的,我希望让我的第三次获取等到前两个请求完成,以便我可以在第三个请求中使用数据。 我是 javascript 的新手,所以我只想知道是否有实现它的好方法

async function getData() {
    res1 = await fetch(url1)
    totalPolice = await res1.json()

    res2 = await fetch(url2)
    totalZone = await res2.json()

    res3 = await fetch(url3)
    data3 = await res3.json()

    data3.length = totalPolice + totalZone
}

我没有测试过。 希望能帮助到你。

我认为一个简单的方法是这样的

async function getAllData(){
    firstApi = await (await fetch('url1')).json();
    secondApi = await (await fetch('url2')).json();
    finalCall = await (await fetch('url from first and second')).json();
    return finalCall;
}

那么您的 function 将返回 promise 并且您可以在此异步 function 的 then 块中反映 UI 中的更改

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM