如何在axios中进行api链调用

时间:2020-05-23 00:14:48

标签: javascript api axios chain

我是axios的新手,我需要获取所有艺术家的结果,然后每个艺术家都有用于封面,专辑和艺术家信息的api网址。 所以有人可以解释一下我如何在此api调用中执行链请求:

    "result": [
        {
            "id_artist": 70170,
            "artist": "Ameritz Karaoke Crew",
            "cover": "https://api.happi.dev//v1/music/cover/70170/artist",
            "api_artist": "https://api.happi.dev/v1/music/artists/70170",
            "api_albums": "https://api.happi.dev/v1/music/artists/70170/albums"
        },

1 个答案:

答案 0 :(得分:0)

我的目标是创建一个从结果中获取项目的函数,并使用各自的数据填充coverapi_artistapi_albums属性。

因此,这里populateArtistWithApiData接受一个artist对象,提出必要的请求并填充该对象。

Promise.all使我可以等待所有艺术家的所有请求完成,然后再解决一系列填充的艺术家。

function populateArtistWithApiData(artist) {
  return new Promise((resolve, reject) => {
    Promise
      .all([
        axios.get(artist.cover),
        axios.get(artist.api_artist),
        axios.get(artist.api_albums),
      ])
      .then(([cover, api_artist, api_albums]) => {
        artist.cover = cover;
        artist.api_artist = api_artist;
        artist.api_albums = api_albums;

        resolve(artist);
      });
  });
}

Promise.all(result.map((artist) => populateArtistWithApiData(artist))).then(
  (populatedArtists) => {
    // There you have the same `artist` objects as before with the properties `cover`,
    // `api_artist`, `api_albums` populated with the data
  }
);