gpt4 book ai didi

javascript - 多次处理同一个请求

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:37 25 4
gpt4 key购买 nike

我正在构建一个用于学习的愚蠢的音乐问答游戏。我需要用来自 deezer api 的相关音乐填充我的 View .

我需要什么:

  1. 获取一个随机类型
  2. 从该流派中获得 5 位艺术家(id + 姓名)
  3. 从每位艺术家那里获得 1 首音乐(姓名 + 链接预览)

所以,I found my way直到第 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);
});
}

*如果我做错了什么请告诉我

最佳答案

如果显式使用 promises(参见下面的 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返回结果(四首歌的 promise ),那么:

// *** 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')
));
}

关于javascript - 多次处理同一个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55989588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com