0

I have this method who performs 3 window.fetch

   const API_URL = 'http://localhost:3000/'
  , API = {
    'getArtistLyric': artist => {
      return fetch(`${API_URL}artist?name=${artist}`)
      .then(res => res.json())
      .then(res => {
        const artistID = JSON.parse(res).message.body.artist_list[0].artist.artist_id;

        console.log('Artist ID is:', artistID);

        fetch(`${API_URL}artist/albums/?artist_id=${artistID}`)
        .then(resp => resp.json())
        .then(resp => {
          const trackID = JSON.parse(resp).message.body.album_list[0].album.album_id;

          console.log('Random Track ID is:', trackID);

          fetch(`${API_URL}artist/album/songsnippet?track_id=${trackID}`)
          .then(response => response.json())
          .then(response => {
            const lyricSnippet = JSON.parse(response).message;

            console.log('Track Id lyric snippet is:', lyricSnippet);
          })
          .catch(err => {
            console.error(err);
          });
        })
        .catch(err => {
          console.error(err);
        });
      })
      .catch(err => {
        console.error(err);
      });
    }
  }

Now i want to call it like this

API.getArtistLyric('Prodigy').then(res).catch(err);

What's the best practice here?

3
  • 1
    There are some returns missing Commented Feb 15, 2018 at 12:41
  • @Andreas looks like but i tried many times, can't get it to work correctly Commented Feb 15, 2018 at 12:42
  • Calling JSON.parse on the result of a response.json() is either a mistake or indicates a weird server response Commented Feb 15, 2018 at 13:09

3 Answers 3

1

If you want to make a chain requests it's better to use async/await :

async func(){
    let response = await /* some request */
    let res = await /* another request */ 
    ...
    return results;
}

Here you can use try/catch syntax and wrap specific request :

try {
    let response = await... 
} catch ( exception)  {
   ...
}

Also you can wrap a couple of requests.

Sign up to request clarification or add additional context in comments.

Comments

1

(async() => {
     const API_URL = 'http://localhost:3000/';
     const API = {
        getArtistLyric: async(artist) => {
        try {
              const res = await fetch(`${API_URL}artist?name=${artist}`);
              const artistID = JSON.parse(res.json()).message.body.artist_list[0].artist.artist_id;

              console.log('Artist ID is:', artistID);

              const resp = await fetch(`${API_URL}artist/albums/?artist_id=${artistID}`);
              const trackID = JSON.parse(resp.json()).message.body.album_list[0].album.album_id;

              console.log('Random Track ID is:', trackID);

              const response = await fetch(`${API_URL}artist/album/songsnippet?track_id=${trackID}`);
            
              const lyricSnippet = JSON.parse(response.json()).message;
              console.log('Track Id lyric snippet is:', lyricSnippet);
              return lyricSnippet;
          } catch (e) {

            console.error(e);
         }
           
        }
      }



    try {
        const art = await API.getArtistLyric('Prodigy');
        console.log(art);
    } catch (e ){
       console.error(e);
    }

})() 

Comments

0

Check out this link regarding chaining promises: https://javascript.info/promise-chaining

Here's the core idea:

It looks like this:

 new Promise(function(resolve, reject) {

  setTimeout(() => resolve(1), 1000); // (*)

}).then(function(result) { // (**)

  alert(result); // 1   return result * 2;

}).then(function(result) { // (***)

  alert(result); // 2   return result * 2;

}).then(function(result) {

  alert(result); // 4   return result * 2;

});

The idea is that the result is passed through the chain of .then handlers.

Here the flow is:

The initial promise resolves in 1 second (*), Then the .then handler is called (**). The value that

it returns is passed to the next .then handler (***) …and so on.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.