Search code examples
javascriptpromisefetch-api

JS Fetch - data is undefined - promise


I want to analyse anwser from http request, display error if needed then return data.

This is what I'm doing right now:

fetch(URL,{method:"GET"})
.then(async response => { await read_errors(response) })
// .then(response => { read_errors(response) }) (Both had been tried)
.then( function(data) { 
    doSomething(data)
})
.catch( error => { display_error(error) })

With this function :

async function read_errors(response) {
    const isJson = response.headers.get('content-type')?.includes('application/json');
    const data = isJson ? await response.json() : null;

    const isText = response.headers.get('content-type')?.includes('text/');
    const text = isText ? await response.text() : null;

    // check for error response
    if (!response.ok) {
        // get error message from body or default to response status
        const error = (data && data.message) || text || response.status;
        console.error("Something went wrong : ",error)
        return Promise.reject(error);
    } else {
        fckng_response = isJson ? data : text
        return Promise.resolve(fckng_response)
    }
}

But I've got TypeError: data is undefined

The answer from server is all right with headers and data OK.

What am I doing wrong?


Solution

  • You're not returning the result of calling read_errors in the .then callback. Either add a return statement or remove the braces ({}).

    .then(response => read_errors(response))
    // no need for async here
    

    It is simpler to completely work with async and await, without mixing it with callbacks.

    try {
        const response = await fetch(URL);
        const data = await read_errors(response);
        doSomething(data);
    } catch (error) {
        display_error(error);
    }