javascript - then 内部嵌套的 fetch 方法
问题描述
我正在使用 fetch API 来获取包含对象数组的 json 文件的 url。我根据需要将对象的值插入到 HTML 文件中。但是,我试图从 json 文件中获取另一个 url。每个对象都有关键的“贡献者”,其 url 值是一个 json 文件。我有可能在 then 方法中使用另一个嵌套的 fetch 方法访问它吗?
'use strict';
{
const root = document.getElementById('root');
const select = document.createElement('select');
root.appendChild(select);
const url = 'https://api.github.com/orgs/HackYourFuture/repos?per_page=100';
fetch(url)
.then(resp => resp.json())
.then(data => {
select.innerHTML = data.sort()
.map(repo => `<option value="${repo.id}">${repo.name}</option>`).join("\n");
select.addEventListener('change', function () {
const chosenRepoId = +this.value;
const currentRepo = data.find(repo => repo.id === chosenRepoId);
document.getElementById('repoInfo').innerHTML = "Repositroy Name: " + currentRepo.name + "<br />" + "Description: " + currentRepo.description + "<br />" + "Forks: " + currentRepo.forks + "<br />" + "Update date: " + currentRepo.updated_at;
// contributors section code
const cntrbutorsUrl = currentRepo.contributors_url;
// fetch the contributors json file
fetch(cntrbutorsUrl)
.then(resp => resp.json)
.then(data => console.log(data));
});
});
// trying to render contributors_url and get its ifno to fill the contribuers square.
}
````js
解决方案
我们可以使用 async/await,
(async function() {
var firstcallresult = await fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json());
var secondcallresult = await fetch('https://jsonplaceholder.typicode.com/todos/' + firstcallresult[1].id)
.then(response => response.json());
console.log(secondcallresult);
})();
推荐阅读
- python - 如何创建一个用户只能在 django 网站上点赞一次的点赞按钮?
- php - 我们可以根据不同的语言使用多种字体使用干预库创建覆盖文本吗?
- javascript - 正则表达式使用 javascript 检查数字长度并允许长度在 6 到 8 之间
- java - 如何从我输入到 FireStore 的数据中向地图添加自定义标记
- php - 如何修复“Access-Control-Allow-Origin”标头的值不等于 Webview Android 上提供的原点?
- c# - OWIN - Authentication.SignOut() 即使在调用注销和删除 cookie 之后似乎也没有删除会话
- r - R包RSEIS - 请举例?
- scrapy - Scrapy Parser - 不会输出数据
- sql - 根据 SQL Server 中其他表的值更新多个列
- android - 以有效的方式管理 android 片段创建?