Home » Javascript » javascript – fetch api .then of calling code is executed first than the service .then which results to undefined data

javascript – fetch api .then of calling code is executed first than the service .then which results to undefined data

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have this function in my service

function getBreeds() {
    const requestOptions = {
        method: "GET"
    };

    return fetch(`${config.apiUrl}breeds`, requestOptions).then(handleResponse);
}

function handleResponse(response) {
    response.text().then(text => {
        const data = text && JSON.parse(text)
        if (!response.ok) {
            const error = (data && data.message) || response.statusText
            return Promise.reject(error)
        }
        return data
    })
}

and it was called in my vuex store

getBreeds({ commit }) {
    commit("getRequest")

    catService.getBreeds()
        .then(
            breeds => { 
                commit("getBreedsSuccess", breeds)  // this line of code executed first even the api is not yet finish
                console.log(breeds)
            },
            error => commit("getFailure", error)
        )
}

What happens is the .then in my vuex store is called first than the .then in my service which result to the breeds value became undefined. How to solve this problem?

How to&Answers:

Your handleResponse isn’t returning anything, so the getBreeds function returns a Promise which resolves as soon as you’ve received the headers (a microtask after the fetch resolves), but before the response has been parsed.

Whenever you have a Promise, you should almost always either await or return it, except at the initiator, to make sure things are chained together properly. Change

response.text().then(text => {

to

return response.text().then(text => {

This will return the .text() Promise up to the caller, to getBreeds and to the caller of getBreeds.

(you should also probably put a .catch onto the end of the catService.getBreeds call, if it doesn’t have one)