Javascript - 链接多个 Fe​​tch 承诺

2022-01-20 00:00:00 http fetch javascript html promise

我有这个方法执行 3 window.fetch

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);
      });
    }
  }

现在我想这样称呼它

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

这里的最佳做法是什么?

What's the best practice here?

推荐答案

如果你想发出链式请求,最好使用 async/await :

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;
}

在这里您可以使用 try/catch 语法并包装特定的请求:

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.

相关文章