Javascript 在地图中获取

Javascript Fetch inside a map

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

Github API return(只有一个项目的例子 returning):

[{
"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))

但是不行!我在控制台中得到这个:

有人可以帮助我吗?提前致谢

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

这里有几件事。您不需要将 .then() 链接到 fetch() 上。 fetch() returns 一个承诺。 Array.prototype.map() returns 一个数组。放在一起,你最终会得到一系列的承诺。您可以使用 Promise.all(arrayOfPs)

解析承诺数组

编辑:在您发表评论并审查您的问题后,我重写了它,以便它从存储库的过滤列表中检索技能。

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));
})();

您有多个问题:

  1. 在地图函数内部你没有return任何结果
  2. 你的 map 函数的结果实际上是另一个 Promise(因为里面有 fetch)。

所以你需要做什么:

  1. Return 来自地图的承诺 - 因此您将拥有一系列承诺
  2. 使用 Promise.all
  3. 等待第 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))

问题是未返回提取,因此 .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);
}