Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

async/await Problem

I'm trying to load a list of podcasts with links to the lastest episodes. I was having problems at first, because my value for the link would be "awaiting Promise." I realized the issue was that my html was rendering before my Promises were fulfilled. I added async/await to my functions to delay the rendering until the GET request was complete, but now none of my html is rendering. any ideas what I'm doing wrong?

const search = document.querySelector('form');
const searchResultsContainer = document.querySelector('#search-results');

function fetchData(url) {
 return fetch(url)
          .then(checkStatus)
          .then(res => res.text())
          .catch(error => console.log('looks like there was a problem ', error));
}

function checkStatus(response) {
  if(response.ok) {
    return Promise.resolve(response);
  } else {
    return Promise.reject(new Error(response.statusText));
  }
}


function searchResults (data) {
  let html = '<ul>';

  data.results.forEach(result => {
    let episodeUrl = getLatestEpisode(result.feedUrl)
    html +=  `
      <li>
        <a href='${episodeURL}'>${result.collectionName}</a>
      </li>
    `;
  });

  html += '</ul>';
  searchResultsContainer.innerHTML = html;
}

function getLatestEpisode (rssFeed) {
  let episodeUrl;
  fetchData(`https://cors-escape.herokuapp.com/${rssFeed}`)
    .then(data => {
      var domParser = new DOMParser();
      doc = domParser.parseFromString(data, 'text/html');
      const latestEpisode = doc.querySelectorAll('enclosure')[0];
      episodeUrl = latestEpisode.getAttribute('url');
      console.log('it works here... ', episodeUrl)
    });
  console.log('but not here... ', episodeUrl)
  return episodeUrl;
}



function searchForPodcast(event) {
  const searchParam = document.querySelector('#search').value;
  event.preventDefault();
  var script = document.createElement('script');
  url = `https://itunes.apple.com/search?term=${searchParam}&media=podcast&callback=searchResults`
  script.src = url
  document.head.appendChild(script);
}

search.addEventListener('submit', searchForPodcast);

Here is a link to my codepen that shows what I'm doing. https://codepen.io/IndigoJack/pen/KrgjGG

Thanks!

1 Answer

I figured it out. The solution wasn't async/await, I just needed to refactor my code so it flowed correctly. Here's the updated version:

const search = document.querySelector('form');
const searchResultsContainer = document.querySelector('#search-results');

function fetchData(url) {
 return fetch(url)
          .then(checkStatus)
          .then(res => res.text())
          .catch(error => console.log('looks like there was a problem ', error));
}


function checkStatus(response) {
  if(response.ok) {
    return Promise.resolve(response);
  } else {
    return Promise.reject(new Error(response.statusText));
  }
}


function searchForPodcast(event) {
  const searchParam = document.querySelector('#search').value;
  event.preventDefault();
  var script = document.createElement('script');
  url = `https://itunes.apple.com/search?term=${searchParam}&media=podcast&callback=searchResults`
  script.src = url
  document.head.appendChild(script);
}


function searchResults (data) {
  const podcasts = data.results;
  const results = data.results.map(result => {
    return {
      podcastName: result.collectionName,
      podcastRss: result.feedUrl,
      lastestEpisodeUrl: '',
      display: true
    };
  });

  getLatestEpisodeUrl(results);
}

function getLatestEpisodeUrl(podcastList) {
    podcastList.forEach(podcast => {
      if (podcast.podcastRss !== undefined) {
        fetchData(`https://cors-escape.herokuapp.com/${podcast.podcastRss}`)
          .then(data => {
            var domParser = new DOMParser();
            doc = domParser.parseFromString(data, 'text/html');
            const latestEpisode = doc.querySelectorAll('enclosure')[0];
            podcast.lastestEpisodeUrl = latestEpisode.getAttribute('url');

            return data;
          })
          .then(data => {
            console.log(podcastList);
            generateHtml(podcastList);
          })
          .catch(error => podcast.display = false);
      }
    });
}

function generateHtml(podcasts) {
  html = '<ul>';
  console.log(podcasts);
  podcasts.forEach(podcast => {
    if (podcast.display) {
      console.log(podcast);
      html += `
        <li>
          <a href='${podcast.lastestEpisodeUrl}'>${podcast.podcastName}</a>
        </li> `
    };
  });
  html += '</ul>';

  searchResultsContainer.innerHTML = html;
}

search.addEventListener('submit', searchForPodcast)