Fetch: reject promise and catch the error if status is not OK?

前端 未结 4 606
抹茶落季
抹茶落季 2020-11-28 22:50

Here\'s what I have going:

import \'whatwg-fetch\';

function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: \'FE         


        
4条回答
  •  感情败类
    2020-11-28 23:45

    Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

    export function fetchVehicle(id) {
        return dispatch => {
            return dispatch({
                type: 'FETCH_VEHICLE',
                payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                    .then(status)
                    .then(res => res.json())    
                    .catch(error => {
                        return Promise.reject()
                    })
                });
        };
    }
    
    
    function status(res) {
        if (!res.ok) {
            throw new Error(res.statusText);
        }
        return res;
    }
    

提交回复
热议问题