我是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"
},
答案 0 :(得分:0)
我的目标是创建一个从结果中获取项目的函数,并使用各自的数据填充cover
,api_artist
和api_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
}
);