0

I'm running a query to the Spotify API for a capstone project in Codecademy for React development, but this is not really an issue involving React at all and more just vanilla JavaScript. (I'm a learner but my web searching still has me completely lost)

I have a search function that's as follows:

  search(searchTerm, _token) {
    let tracks = {};
    const searchTerms = [
      'type=track',
      `q=${searchTerm}`
    ];
    const searchUrl = searchEndpoint + '?' + searchTerms.join('&');
    return fetch(searchUrl, {
      headers: {
        Authorization: 'Bearer ' + _token
      }
    })
    .then((response) => {
      return response.json()
      ;
    })
    .then((jsonResponse) => {
      return jsonResponse.tracks.items.map((track) => {
        const tracksObj = {
          id: track.id,
          name: track.name,
          artist: track.artists[0].name,
          album: track.album.name,
          uri: track.uri
        };
        return  tracksObj;
      });
    });
  }
};

The request is sent just fine and I'm even able to extract the data. But the return statement is a promise pending but it has the fulfilled values.

When I pass "This must be the place" and a valid access token and log the function call, here's what it looks like:

console for fulfilled promise

now if I change to log the map function in the final call, it logs exactly what I'm after. Here's that code and log:

    .then((jsonResponse) => {
      console.log(jsonResponse.tracks.items.map((track) => {
        const tracksObj = {
          id: track.id,
          name: track.name,
          artist: track.artists[0].name,
          album: track.album.name,
          uri: track.uri
        };
        return  tracksObj;
      }));
    });

Logging response map

So...how to I get the values out of the return statement rather than just the promise?

Regards

  • 2
    I'm not sure that huge post is the best way to start, but yes, this question is clearly not something that requires a new answer. The explanation and solution are the very foundation of Promises, so look them up. Come back if you have a problem that isn't exactly how things are supposed to work ;) – Touffy Aug 02 '20 at 17:05

0 Answers0