[英]Merge api request using promise
Due to the api of a plugin I'm using not working properly. 由于使用了插件的api,因此我无法正常使用。 I need to merge the two different requests. 我需要合并两个不同的请求。 I am using the thunk below. 我在用下面的东西。
I can get a response but I cannot seem to check for response.ok
, and return the combined data: 我可以获得响应,但是似乎无法检查response.ok
并返回合并的数据:
export function fetchCategories() {
const firstPage =
"http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/categories?per_page=60&page=1";
const secondPage =
"http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/categories?per_page=60&page=2";
return dispatch => {
dispatch(isLoading(true));
Promise.all([fetch(firstPage), fetch(secondPage)])
.then(response => {
// check for ok here
response.ForEach(response => {
if (!response.ok) throw Error(response.statusText);
});
dispatch(isLoading(false));
return response;
})
.then(response => response.json())
// dispatch combined data here
.then(data => dispatch(fetchSuccessCategories(data)))
.catch(() => dispatch(hasErrored(true)));
};
}
Any ideas? 有任何想法吗?
You are doing the check for .ok
fine because it's in a loop, but your response
is actually an array of two Response objects, it does not have a .json()
method. 您正在检查.ok
罚款,因为它处于循环中,但是您的response
实际上是两个Response对象的数组,它没有.json()
方法。 You could do Promise.all(responses.map(r => r.json()))
, but I would recommend to write a helper function that does the complete promise chaining for one request and then call that twice: 您可以执行Promise.all(responses.map(r => r.json()))
,但是我建议编写一个辅助函数,该函数对一个请求执行完整的诺言链,然后调用两次:
function fetchPage(num) {
const url = "http://wordpress.rguc.co.uk/index.php/wp-json/tribe/events/v1/categories?per_page=60&page="+num;
return fetch(url).then(response => {
if (!response.ok)
throw new Error(response.statusText);
return response.json();
});
}
export function fetchCategories() {
return dispatch => {
dispatch(isLoading(true));
Promise.all([fetchPage(1), fetchPage(2)]).then(data => {
dispatch(isLoading(false));
dispatch(fetchSuccessCategories(merge(data)));
}, err => {
dispatch(isLoading(false));
dispatch(hasErrored(true));
});
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.