如何从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());
});
});
};
}
答案 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
一起使用。