首页 文章

Fetch API无法识别response.status

提问于
浏览
0

我只是想尝试使用Fetch API获取数据 . 这是我的代码

function status(response) {  
    return response.json().then( data => {
        if(response === 200) {  
            return data
        }else if(response.status === 400){
            let message = data.error.error.error[0]
            return Promise.reject({status: response.status, message});
        }else if(response.status === 401){
            let message = data.message
            return Promise.reject({status: response.status, message});
        }else{  
            return Promise.reject({status: response.status, data});    
        }  
    })
    }

export function getAgenda(limit, offset, status){
    return (dispatch)=>{
        dispatch({
            type: 'FETCH_AGENDA_REQUEST'
        })

        const token = loadCred().token

        api.fetchAgenda(limit, offset, status, token)
            .then(status) 
            .then(function(data){
                console.log(data) // this is printed in console
                dispatch({
                  type: 'FETCH_AGENDA_SUCCESS',
                  payload: { 
                    ...data,
                    totalPages: Math.ceil(data.totalRows / limit) 
                    }
                })  
            }).catch(function(error) {
                console.log(error) // not this one
                dispatch({
                  type: 'FETCH_AGENDA_ERROR',
                  payload: {
                    error
                  }
                });
            })
    }
}

由于Fetch API将400视为已解析的Promise,因此我尝试使用Status函数首先过滤它们 . 但事实证明,错误401被认为是已解决而非被拒绝 . 我试图检查但是控制台中的错误没有被catch打印 .

error in console not printed by catch

1 回答

  • 0

    您的状态函数可以返回已解决的promise或者被拒绝的promise(抛出错误会使catch语句阻塞它) .

    function main() {
        // call fetchAgenda api
        api.fetchAgenda(
        // what you are doing here
            // ...
        // return a response object
        ).then(
            response => status(response)
        // resolved promise returned by status call
        ).then(
            data => console.log(data);
        // rejected promise returned by status call
        ).catch(
            error => console.log(error);
        );
    }
    
    function status(response) {
        // if response is ok (200 - 299) or is less than 400
        if (response.ok || response.status < 400) {
            // it's good, convert it into json
            return response.json();
        }
        else {
            // response isn't fine, reject promise...
            return Promise.reject(response);
            // ... or throw an error
            // return throw Error(response);
        }
    }
    

相关问题