我正在执行一系列 async await 提取请求,每个请求都依赖于先前请求中找到的变量。我现在设置它的方式是通过一系列专用函数,每个函数返回我需要的变量。随后,我有了一个.then链,在该链上传递,使用了相关变量,并将其最终放置在html中。这些链有时最多可以包含6个功能。
它可能看起来像这样:
fetch1(artist_name) //returns an artistID
.then(artistID => fetch2(artistID, albumName)) //uses the artistID and album name to return a trackID
.then(trackID => fetch3(trackID)) //uses the trackID to return track credits
(结果1)
fetch1(artist_name)
.then(artistID => fetch2(artistID, albumName))
.then(trackName => fetch4(trackName))
(result2)
这可以正常工作,但是我很好奇这是否是最有效的处理方式,因为对于结果1和2,我重复fetch1和fetch2,依赖于第二次提取后返回的同一JSON对象来进行第三次提取:
fetch1> fetch2 > fetch3>结果1
fetch1> fetch2 > fetch4>结果2
谁能指出我的资源,或提供一个可以更好地实现这一目标的示例?我知道javascript是异步工作的(因此异步获取)。
我的提取请求通常如下所示:
async function fetch1(artist_name) {
try {
var url = `http://musicbrainz.org/ws/2/artist/?&fmt=json&limit=1&query=artist:"${artist_name}"`
let response = await fetch(url);
let data = await response.json()
let mbArtistID = data["artists"][0].id
return mbArtistID
} catch (error) {
console.log(error);
}