метод вложенного извлечения внутри тогда - PullRequest
1 голос
/ 07 июня 2019

Я использую API выборки для получения URL-адреса файла json, который содержит массив объектов. Я получил значения объектов, вставленных в файл HTML, как мне было нужно. Однако я пытаюсь получить другой URL из файла json. у каждого объекта есть ключ 'contributors' со значением url, являющимся файлом json. возможно ли, что я получу доступ к нему с помощью другого метода вложенного извлечения внутри метода then

'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

1 Ответ

0 голосов
/ 07 июня 2019

Мы можем использовать 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);
            })();
...