data.json不是函数错误

时间:2018-08-10 11:00:47

标签: reactjs es6-promise

如何从Promise.all中获取数据?

我当前收到错误消息:

可能的未处理的承诺拒绝(id:0): TypeError:data.json不是函数 TypeError:data.json不是函数

export function fetchEvents() {
    let pagesRequired = 0;
    return dispatch => {
        dispatch(isLoading(true));
        fetch(
            "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/events?per_page=50&categories=107"
        )
            .then(response => {
                return response;
            })
            .then(response => response.json())
            .then(data => {
                const apiPromises = [];
                pagesRequired = data.total_pages;

                for (let i = pagesRequired; i > 0; i--) {
                    apiPromises.push(
                        fetch(
                            "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/events?per_page=50&categories=107&page=" +
                                i
                        )
                    );
                }
                Promise.all(apiPromises)
                    .then(response => {
                        return response;
                    })
                    .then(data => {
                        console.log(data.json());
                    });
            });
    };
}

2 个答案:

答案 0 :(得分:1)

Promise.all返回一个结果数组,如果期望此数组中的Response对象,则应首先选择它:response[0].json()

答案 1 :(得分:0)

应该是:

for (let i = pagesRequired; i > 0; i--) {
  apiPromises.push(
    fetch(
      "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/events?per_page=50&categories=107&page=" +
      i
    ).then(resp => resp.json())
  );
}
Promise.all(apiPromises)
  .then(data => {
    console.log(data);
  });

apiPromises应该收集解决最终需要的承诺。然后执行Promise.all(apiPromises)以获取实际数据。这是small demo with fetch,显示Promise.all API如何与fetch一起使用。