gpt4 book ai didi

javascript - 如何逃离这个回调 hell

转载 作者:行者123 更新时间:2023-12-05 05:48:43 27 4
gpt4 key购买 nike

我目前正在尝试从公共(public) API 获取有关一个国家及其邻国的数据,以在我的 html 上呈现。
renderCountry( ) 是一个函数,用于在我的 html 上实现我将收到的数据。
我还排除了一些不必要的代码,我认为这些代码在这种特殊情况下并不重要。

这是我获取数据的方式:

const getCountryAndNeighbour = function(country) {
fetch(`https://restcountries.com/v2/name/${country}`)
.then(response => response.json())
.then(data => {
renderCountry(data[0]);
const neighbour = data[0].borders;
neighbour.forEach(country => {
fetch(`https://restcountries.com/v2/alpha/${country}`)
.then(response => response.json())
.then(data => renderCountry(data, `neighbour`))
});
})
}

在这里,您将看到回调 hell 架构。有什么想法可以逃避吗?提前致谢。

最佳答案

您可以尝试使用 async/await .您可以在 function 关键字之前添加 async 并根据需要添加 await 。请参阅下面的实际操作:

const getCountryAndNeighbour = async function (country) {
const res = await fetch(`https://restcountries.com/v2/name/${country}`)
const data = await res.json();

renderCountry(data[0]);
const neighbour = data[0].borders;
await Promise.all(
neighbour.map(async country => {
let response = await fetch(`https://restcountries.com/v2/alpha/${country}`)
response = await response.json();
return renderCountry(response, 'neighbour');
});
);
}

关于javascript - 如何逃离这个回调 hell ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70777325/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com