Serviceworker Bug event.respondWith

Viewed 7238

My serviceworker has the logic that when a fetch event happens,first it fetches an endpoint which contains some boolean value (not the event.request.url) and check the value , based on the value i am calling event.respondWith() for the current fetch event, where i am serving the response from cache.But i am getting the following error ,

Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The fetch event has already been responded to

I checked here that this error is throws when m_state is not equal to Initial

if (m_state != Initial) {
    exceptionState.throwDOMException(InvalidStateError, "The fetch event has already been responded to.");
    return;
}

I am doubting that since i am having an additional fetch event somehow it is consuming the previous fetch event,it is changing the m_state variable,though i am not fetching the event url.I am not sure what could be the reason and what is the solution for it.But why is it saying

I am pasting my code snippet below.

function fetchEvt(event) {        
    check().then(function (status) {
        if (status === 0) {
            handleRequest(event);
        }
    });
}

function checkHash() {
    return new Promise(function (resolve) {
        fetch(endpoint, { credentials: 'include' }).then(function (response) {
            return response.text();
        }).then(function (text) {
            resolve(text);
        });
    }
}

function handleRequest(event) {
    event.respondWith(caches.match(event.request.url).then(function (Response) {
        if (Response) {
            return Response;
        }
        return fetch(event.reuqest);
    }));
}

The event.respondWith part is throwing the error.Please suggest how to solve this problem.

edit :

function handleRequest(event) {
    event.respondWith(checkHash().then(function (status) {
        if (status === true) {
            caches.match(event.request.url).then(function (Response) {
                if (Response) {
                    return Response;
                }
                return fetch(event.reuqest);
            });
        } else if (status === false) return fetch(event.reuqest);
}));
2 Answers
Related