[英]Javascript - Chain multiple Fetch promises
I have this method who performs 3 window.fetch 我有这种方法执行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);
});
}
}
Now i want to call it like this 现在我想这样称呼它
API.getArtistLyric('Prodigy').then(res).catch(err);
What's the best practice here? 这里的最佳做法是什么?
If you want to make a chain requests it's better to use async/await : 如果要发出链请求,最好使用async / await:
async func(){
let response = await /* some request */
let res = await /* another request */
...
return results;
}
Here you can use try/catch syntax and wrap specific request : 在这里,您可以使用try / catch语法并包装特定请求:
try {
let response = await...
} catch ( exception) {
...
}
Also you can wrap a couple of requests. 您也可以包装几个请求。
(async() => { const API_URL = 'http://localhost:3000/'; const API = { getArtistLyric: async(artist) => { try { const res = await fetch(`${API_URL}artist?name=${artist}`); const artistID = JSON.parse(res.json()).message.body.artist_list[0].artist.artist_id; console.log('Artist ID is:', artistID); const resp = await fetch(`${API_URL}artist/albums/?artist_id=${artistID}`); const trackID = JSON.parse(resp.json()).message.body.album_list[0].album.album_id; console.log('Random Track ID is:', trackID); const response = await fetch(`${API_URL}artist/album/songsnippet?track_id=${trackID}`); const lyricSnippet = JSON.parse(response.json()).message; console.log('Track Id lyric snippet is:', lyricSnippet); return lyricSnippet; } catch (e) { console.error(e); } } } try { const art = await API.getArtistLyric('Prodigy'); console.log(art); } catch (e ){ console.error(e); } })()
Check out this link regarding chaining promises: https://javascript.info/promise-chaining 查看有关链接承诺的此链接: https : //javascript.info/promise-chaining
Here's the core idea: 这是核心思想:
It looks like this:
看起来像这样:
new Promise(function(resolve, reject) { setTimeout(() => resolve(1), 1000); // (*) }).then(function(result) { // (**) alert(result); // 1 return result * 2; }).then(function(result) { // (***) alert(result); // 2 return result * 2; }).then(function(result) { alert(result); // 4 return result * 2; });
The idea is that the result is passed through the chain of .then handlers.
这个想法是将结果通过.then处理程序链传递。
Here the flow is:
这里的流程是:
The initial promise resolves in 1 second (*), Then the .then handler is called (**).
初始承诺在1秒钟内解析(*),然后将.then处理程序称为(**)。 The value that
的价值
it returns is passed to the next .then handler (***) …and so on.
它返回的内容将传递给下一个.then处理程序(***)……等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.