Javascript-链接多个Fetch Promise [英] Javascript - Chain multiple Fetch promises

查看:61
本文介绍了Javascript-链接多个Fetch 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.

这篇关于Javascript-链接多个Fetch Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆