Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading