Если использовать обещания явно (см. Ниже для async
функций), я, вероятно, подхожу к этому так; см. ***
комментарии для объяснения:
// *** Give yourself a helper function so you don't repeat this logic over and over
function fetchJson(errmsg, ...args) {
return fetch(...args)
.then(response => {
if (!response.ok) { // *** .ok is simpler than .status == 200
throw new Error(errmsg);
}
return response.json();
});
}
function deezer() {
// *** Not sure why you're using Request here?
const reqGenero = new Request('https://api.deezer.com/genre');
fetchJson('Erro ao pegar gêneros', reqGenero)
.then(generos => {
/* pega genero aleatorio */
var generoId = generos.data[Math.floor(Math.random() * 10 + 1)].id;
//console.log('\ngenero... ' + generoId);
return fetchJson('Erro ao pegar artistas', 'https://api.deezer.com/genre/' + generoId + '/artists')
})
.then(artistas => {
/* 1 música de 4 artistas */
// *** Use Promise.all to wait for the four responses
return Promise.all(artistas.data.slice(0, 4).map(
entry => fetchJson('Erro ao pegar música', 'https://api.deezer.com/artist/' + entry.id + '/top')
));
})
.then(musica => {
// *** Use musica here, it's an array of the music responses
})
.catch(error => {
console.error(error);
});
}
Предполагается, что вы хотите использовать результаты в deezer
. Если вы хотите от deezer
до вернуть результаты (обещание четырех песен), тогда:
// *** Give yourself a helper function so you don't repeat this logic over and over
function fetchJson(errmsg, ...args) {
return fetch(...args)
.then(response => {
if (!response.ok) { // *** .ok is simpler than .status == 200
throw new Error(errmsg);
}
return response.json();
});
}
function deezer() {
const reqGenero = new Request('https://api.deezer.com/genre');
return fetchJson('Erro ao pegar gêneros', reqGenero) // *** Note the return
.then(generos => {
/* pega genero aleatorio */
var generoId = generos.data[Math.floor(Math.random() * 10 + 1)].id;
//console.log('\ngenero... ' + generoId);
return fetchJson('Erro ao pegar artistas', 'https://api.deezer.com/genre/' + generoId + '/artists')
})
.then(artistas => {
/* 1 música de 4 artistas */
// *** Use Promise.all to wait for the four responses
return Promise.all(artistas.data.slice(0, 4).map(
entry => fetchJson('Erro ao pegar música', 'https://api.deezer.com/artist/' + entry.id + '/top')
));
});
// *** No `then` using the results here, no `catch`; let the caller handle it
}
Версия функции async
этой второй:
// *** Give yourself a helper function so you don't repeat this logic over and over
async function fetchJson(errmsg, ...args) {
const response = await fetch(...args)
if (!response.ok) { // *** .ok is simpler than .status == 200
throw new Error(errmsg);
}
return response.json();
}
async function deezer() {
const reqGenero = new Request('https://api.deezer.com/genre');
const generos = await fetchJson('Erro ao pegar gêneros', reqGenero);
var generoId = generos.data[Math.floor(Math.random() * 10 + 1)].id;
//console.log('\ngenero... ' + generoId);
const artistas = await fetchJson('Erro ao pegar artistas', 'https://api.deezer.com/genre/' + generoId + '/artists');
/* 1 música de 4 artistas */
// *** Use Promise.all to wait for the four responses
return Promise.all(artistas.data.slice(0, 4).map(
entry => fetchJson('Erro ao pegar música', 'https://api.deezer.com/artist/' + entry.id + '/top')
));
}