JS Fetch: How to return response with body or error?

I am struggling with this code moving from ajax to fetch. I want to call an API and

  • not return until done
  • return the response object with status
  • return the response object with json
  • return the response object with an error message if exists
    This code is returning prior to completion causing an uncaught error, and forcing the browser to repaint (Chrome). I am unable to figure out why. If I step through the code slowly it always completes.
    function getAPI(url, requestOptions) {
    return fetch(url, requestOptions).then((response) => {
        return response.json().then(json => {
            response.json = json;
            console.log(response);
            return response;
        })
        .catch(error => {
            console.error('Error:', error);
            response.error = error;
            return response;
        });
    }).catch(error => {
        console.error('Error:', error);         
        response.error = error;
        return response;
    });
}

14 thoughts on “JS Fetch: How to return response with body or error?”

Leave a Comment