简体   繁体   中英

Merge api request using promise

Due to the api of a plugin I'm using not working properly. 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:

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. 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:

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));
        });
    };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM