Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serviceworker Bug event.respondWith

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);
}));
like image 321
biswpo Avatar asked Mar 17 '16 14:03

biswpo


1 Answers

You need to call event.respondWith synchronously when handling fetch event. If you don't, browser assumes it should proceed with handling the request. That's why when you get around to calling respondWith in your code the request is already handled and you see the fetch event has already been responded to exception.

In other words: try calling your checkHash inside of handleRequest and not the other way around.

like image 172
pirxpilot Avatar answered Oct 15 '22 14:10

pirxpilot