我在做一个愚蠢的音乐小游戏来学习。我需要用deezer api的相关音乐填充我的观点。
我需要的是:
所以,我找到了我的路直到第3步
但是我不知道如何正确地发送相同的请求4次(每个艺术家),我的研究到目前为止还没有给我任何帮助
function deezer() {
const reqGenero = new Request('https://api.deezer.com/genre');
fetch(reqGenero)
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Erro ao pegar gêneros');
}
})
.then(generos => {
/* pega genero aleatorio */
var generoId = generos.data[Math.floor(Math.random() * 10 + 1)].id;
//console.log('\ngenero... ' + generoId);
return fetch('https://api.deezer.com/genre/' + generoId + '/artists')
})
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Erro ao pegar artistas');
}
})
.then(artistas => {
/* 1 música de 4 artistas */
var artistasIds = [];
for(var i = 0; i <= 4; i++) {
artistasIds.push(artistas.data[i].id);
console.log('\nId: ' + artistasIds[i]);
// CAN I SEND THIS REQUEST 4 TIMES?
return fetch('https://api.deezer.com/artist/' + ids + '/top');
}
})
.catch(error => {
console.error(error);
});
}
*如果我做错了什么,请告诉我
发布于 2019-05-05 07:39:11
如果显式地使用承诺(关于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')
));
}
发布于 2019-05-05 07:20:20
您可以使用Promise#all创建4个请求并等待它们全部完成。
.then(artistas => {
/* 1 música de 4 artistas */
const artistasPromises = artistas.data.map(artista =>
fetch("https://api.deezer.com/artist/" + artista.id + "/top").catch(
err => ({ error: err })
)
);
return Promise.all(artistasPromises);
}).then(musicList => {
console.log(musicList);
});
注意catch()
。这确保即使fetch失败,也不会忽略其他fetch结果。这是因为Promise#all的工作方式。因此,您需要在musicList
上迭代并检查是否存在形状{ error: /* error object */ }
的任何对象,并在处理列表时忽略它。
发布于 2019-05-05 07:20:24
您可以替换语句
// CAN I SEND THIS REQUEST 4 TIMES?
return fetch('https://api.deezer.com/artist/' + ids + '/top');
使用
const fetchResults = [];
artistasIds.forEach(function(ids){
fetchResults.push(fetch('https://api.deezer.com/artist/' + ids + '/top'));
});
return Promise.all(fetchResults);
在此情况下,您将从每个艺术家那里得到一组顶级音乐的值。我还没有检查给定的API,但理想情况下,它应该能工作。
https://stackoverflow.com/questions/55989588
复制相似问题