多次处理相同的请求

时间:2019-05-05 06:58:43

标签: javascript request fetch-api

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

我需要什么:

  1. 获得随机体裁
  2. 从此流派(id +名称)中获得5位艺术家
  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);
        });      
}

*请让我知道我做错什么了

4 个答案:

答案 0 :(得分:2)

如果显式使用诺言(请参见下面的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')
    ));
}

答案 1 :(得分:1)

您可以使用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()。这样可以确保即使提取失败,其他提取结果也不会被忽略。这是因为Promise#all的工作方式。因此,您需要遍历musicList并检查是否存在任何形状为{ error: /* error object */ }的对象,并在处理列表时将其忽略。

答案 2 :(得分:1)

您可以替换语句

// 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进行检查,但理想情况下应该可以使用。

答案 3 :(得分:1)

是的,您可以发出5个请求(而不是4个0-4),然后等待每个请求完成。 使用Array.prototype.map创建一个请求承诺数组。(优先于for-forEach和array.push)

Promise.all 等待所有的诺言完成,如果没有失败,它将返回已解决的响应数组。

.then(artistas => {
  /* 1 música de 4 artistas */
  var artistasIds = [];
  let ids = artistas.data.map(artist => artist.id).slice(0, 4);
  requests = ids.map(id => fetch(`https://api.deezer.com/artist/${id}/top`));
  return Promise.all(requests);
  }
})