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

1 thought on “JS Fetch: How to return response with body or error?”

  1. I think you wanted to get this result

    async function getAPI(url, requestOptions) {
        let result;
    
        await fetch(url, requestOptions)
            .then(response => response.json())
            .then(response => result = response)
            .catch(error => console.error('Error:', error))
    
        return result;
    }
    

    Using:

    await getAPI('https://jsonplaceholder.typicode.com/todos/1')
    

    and it returns response.

    //
    Edited, with adding status

    async function getAPI(url, requestOptions) {
        let result;
    
        await fetch(url, requestOptions)
            .then(response => response.json())
            .then(response => result = { status: 'success', response })
            .catch(error => result = { status: 'error', error })
    
        return result;
    }
    
    Reply

Leave a Comment