- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我目前正在尝试从公共(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/
我正在使用 C 语言在 UNIX 环境中开发网络服务器。目前,我已经完成了对进程的限制,但现在我无法使用系统日志和记录到文件选项,这主要是由于更改了根路径。 程序的新根路径是它的目录。我无法从它逃脱到
有人知道为什么 mysql_real_escape_string() 函数在引号或双引号前添加三个反斜杠,而不是一个吗? 我在检索内容时遇到问题;有一个额外的反斜杠。这仅发生在 Aruba MySQL
我有代码,点击分区显示。它禁用我的滚动条,当用户单击禁用按钮 (img) 时,我想退出我的 preventDefault 函数,因为当我想使用滚动条时,它再次被禁用。 如您所见,我返回了默认的 css
我在我的 RoR3 应用程序中使用 Maruku。但问题是,当我在使用 Maruku 之前使用 h(text) 方法从数据库中转义文本时,它会将 > 转义为 > 所以 Maruku 不会将其视为 bl
我已经研究了大约一个小时,研究如何让 NPC “排斥”,意思是在 Unity3d 中逃离玩家。我到处搜索这个,我发现了很多关于如何让 NPC 跑向玩家但从不排斥的东西。我是游戏开发的新手,所以我不知道
我在 StackOverflow 中阅读了许多类似的场景,但没有一个解决这种情况: 我提交了我的第一个应用程序版本,其中还包括应用程序内购买 (IAP)。我将应用内购买产品附加到应用的新版本。然后我按
最近,我开始从事一个软件平台元素,使用我自己的 java 制作的应用程序服务器和 Adobe Flash 作为客户端技术,就像我过去一直做的那样,但这项新工作是一个非常长期的元素,而今天的 Fla
我是一名优秀的程序员,十分优秀!