繁体   English   中英

使用Promise合并API请求

[英]Merge api request using promise

由于使用了插件的api,因此我无法正常使用。 我需要合并两个不同的请求。 我在用下面的东西。

我可以获得响应,但是似乎无法检查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)));
    };
}

有任何想法吗?

您正在检查.ok罚款,因为它处于循环中,但是您的response实际上是两个Response对象的数组,它没有.json()方法。 您可以执行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.

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