gpt4 book ai didi

map 内的Javascript Fetch

转载 作者:行者123 更新时间:2023-12-03 07:02:35 24 4
gpt4 key购买 nike

我有一个网站/作品集,我在其中使用 Github API 显示我的所有项目。我的目标是为这些项目创建一个过滤器,因此我在一些存储库的根目录中创建了一个名为“built-with.json”的文件,该文件存在于 只有两个存储库仅出于测试目的,这是我在项目中使用的一系列技术(例如:[“React”,“Javascript”,...])。所以我需要获取 Github APi(它运行良好的那部分),然后获取该文件,并返回一个新的项目数组,但使用“filters”键,其中值是“built-with.json”中的数组.例子:
Github API 返回(仅返回一个项目的示例):

[{
"id": 307774617,
"node_id": "MDEwOlJlcG9zaXRvcnkzMDc3NzQ2MTc=",
"name": "vanilla-javascript-utility-functions",
"full_name": "RodrigoWebDev/vanilla-javascript-utility-functions",
"private": false
}]
我需要的新对象数组:
[{
"id": 307774617,
"node_id": "MDEwOlJlcG9zaXRvcnkzMDc3NzQ2MTc=",
"name": "vanilla-javascript-utility-functions",
"full_name": "RodrigoWebDev/vanilla-javascript-utility-functions",
"private": false,
"filters": ["HTML5", "CSS3", "JS", "React"]
}]
这就是我所做的:
const url = "https://api.github.com/users/RodrigoWebDev/repos?per_page=100&sort=created";
fetch(url)
.then((response) => response.json())
.then((data) => {
return data.map(item => {
//item.full_name returns the repositorie name
fetch(`https://raw.githubusercontent.com/${item.full_name}/master/built-with.json`)
.then(data => {
item["filters"] = data
return item
})
})
})
.then(data => console.log(data))
但它不起作用!我在控制台中得到了这个:
enter image description here
有人可以帮助我吗?提前致谢
注意:抱歉,如果您发现一些语法错误,我的英语正在进行中

最佳答案

这里有几件事。您不需要将 .then() 链接到 fetch()。 fetch() 返回一个 promise 。 Array.prototype.map() 返回一个数组。放在一起,你最终会得到一系列的 promise 。您可以使用 Promise.all(arrayOfPs) 解析 promise 数组
编辑:在您发表评论并查看您的问题之后,我重写了它,以便它从过滤的存储库列表中检索技能。

const url = `https://api.github.com/users/RodrigoWebDev/repos?per_page=100&sort=created`;

(async() => {
// Final results
let results;
try {
// Get all repositories
const repos = await fetch(url).then((res) => res.json());
const responses = await Promise.all(
// Request file named 'build-with.json' from each repository
repos.map((item) => {
return fetch(
`https://raw.githubusercontent.com/${item.full_name}/master/built-with.json`
);
})
);
// Filter out all non-200 http response codes (essentially 404 errors)
const filteredResponses = responses.filter((res) => res.status === 200);
results = Promise.all(
// Get the project name from the URL and skills from the file
filteredResponses.map(async(fr) => {
const project = fr.url.match(/(RodrigoWebDev)\/(\S+)(?=\/master)/)[2];
const skills = await fr.json();
return {
project: project,
skills: skills
};
})
);
} catch (err) {
console.log("Error: ", err);
}
results.then((s) => console.log(s));
})();

关于 map 内的Javascript Fetch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64617355/

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