Skip to content
Advertisement

await does not affect async function

Hi i’m fairly new to javascript and I’m having a problem with my async function inside the AddEventListener method that is not awaiting the fetch result, so when i try to console.log(track_info.tracks) it prints out undefined.

const getTrack = async (urlTrack) => {
  const result = await fetch(urlTrack, {          
    method: "GET",
    headers: { 'Authorization' : 'Bearer ' + localStorage.getItem("access_token")}
  });
  
  const data = await result.json();
  return data;
}

songBtn.addEventListener('click', async () => {
  var searchSongBar = document.getElementById('search_song').value; //gets string from searchbar
  sessionStorage.setItem("title", searchSongBar); //saves the string as title in sessionStorage
       
  const trackTitle = sessionStorage.getItem('title'); //takes title and puts it inside the variable to use in the url
  var urlTrack = `https://api.spotify.com/v1/search?q=${trackTitle}&type=track&market=us&limit=1&include_external=false`;
  var track_info = getTrack(urlTrack);
  console.log(track_info.tracks)
});

Advertisement

Answer

Solution

You need to add an await to the call of getTrack. var track_info = await getTrack(urlTrack);

Helpful Tips

How to await fetch You do not need to await both fetch and result.json as you are awaiting an already returned result. You can await result.json, however awaiting fetch in this instance is not needed since fetch is returning a promise.

How to await promises You created an asynchronous function, and just like fetch, you need to await the result before continuing. A good rule of thumb is that you should await an asynchronous function whenever you need to reference the data returned. You awaited fetch() so you could access result.json(). Likewise, you await getTrack() so you can console.log its return value.

const getTrack = async (urlTrack) => {

    const result = await fetch(urlTrack, {          
        method: "GET",
        headers: { 'Authorization' : 'Bearer ' + 
            localStorage.getItem("access_token")}
    });

    return result.json();
}


      

songBtn.addEventListener('click', async () => {
    var searchSongBar = document.getElementById('search_song').value; //gets string from searchbar
    sessionStorage.setItem("title", searchSongBar); //saves the string as title in sessionStorage
    const trackTitle = sessionStorage.getItem('title'); //takes title and puts it inside the variable to use in the url
    var urlTrack = `https://api.spotify.com/v1/search?q=${trackTitle}&type=track&market=us&limit=1&include_external=false`;

    var track_info = await getTrack(urlTrack);
    console.log(track_info.tracks);
});
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement