Javascript Fetch和Map无法正常工作

时间:2017-09-14 16:57:42

标签: javascript

我正在尝试获取多页api并将json放在数组中。我已经设置好它所需的数量,并设置了正确数量的承诺。我得到了50多个不同的回复。但是,当我尝试映射每个响应时,它只会拉取第一组数据并将其重复推送到数组。我做得不好?

var data;
    fetch(URL_ARTISTS3,{
        method:'GET'
    })
    .then(response => response.json())
    .then(json => {
        data =json;
        const apiPromises = [];
        var pagesRequired = Math.ceil(json.setlists["@total"] / json.setlists["@itemsPerPage"]);

        for (let i=pagesRequired; i>0;i--) {
            var fetchurl = URL_ARTISTS3 + '?page = ' + i;
            apiPromises.push(fetch(fetchurl, {
              method: "GET",
              body: json
            }));
        }

        Promise.all(apiPromises)
        .then(responses => {
            var processedResponses = [];
            responses.map(response => response.json()
                .then(json => {
           /****THIS LINE ADDS THE SAME JSON RESPONSE MULTIPLE TIMES*****/
                    processedResponses.push(json.setlists.setlist);
                })
             )   
            console.log('processedResponses: ', processedResponses)     

        });

1 个答案:

答案 0 :(得分:1)

我不确定它是否解决了问题,但有一个问题是您在解决承诺之前正在记录processedResponses

您可以通过移动response.json()电话来简化您的代码:

apiPromises.push(
  fetch(fetchurl, {method: "GET", body: json})
    .then(response => response.json())
    .then(json => json.setlists.setlist);
);

// ...

Promise.all(apiPromises).then(processedResponses => console.log(processedResponses));