Javascript 在地图内获取

问题描述 投票:0回答:3

我有一个网站/作品集,我使用 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))

但这不起作用!我在控制台中得到这个:

有人可以帮助我吗?预先感谢

注意:如果您发现一些语法错误,我很抱歉,我的英语还在进行中

javascript arrays fetch-api github-api
3个回答
11
投票

这里有几件事。您不需要将 .then() 链接到 fetch() 上。 fetch() 返回一个承诺。 Array.prototype.map() 返回一个数组。总而言之,你最终会得到一系列的承诺。您可以使用 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));
})();


2
投票

问题是提取没有被返回,因此 .map() 返回未定义。我可以建议使用 async-await 的解决方案吗?

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

getData(url).then(data => console.log(data));
  
async function getData(url){
  const response = await fetch(url);
  const data = await response.json();
  const arrOfPromises = data.map(item => fetch(`https://raw.githubusercontent.com/${item.full_name}/master/built-with.json`)
  );
  return Promise.all(arrOfPromises);
}


1
投票

您有多个问题:

  1. 在地图函数内部,您不会返回任何结果
  2. map 函数的结果实际上是另一个 Promise(因为内部有 fetch)。

那么你需要做什么:

  1. 从地图返回承诺 - 因此你将拥有一系列承诺
  2. 使用 Promise.all 等待第 1 点中的所有承诺

类似这样的:



    var url1 = "https://api.github.com/users/RodrigoWebDev/repos?per_page=100&sort=created";
    var datum = fetch(url1)
      .then((response) => response.json())
      .then((data) => {
          return Promise.all(data.map(item => {
            //item.full_name returns the repositorie name
            return fetch(`https://raw.githubusercontent.com/${item.full_name}/master/built-with.json`)
              .then(data => {
                item["filters"] = data
                return item
              })
          }));
        }).then(data => console.log(data))

© www.soinside.com 2019 - 2024. All rights reserved.