Is it ever necessary to use a waitUntil
inside a respondWith
(itself within a fetch
event)? Doesn't respondWith
already waitUntil
it receives a resolved promise?
Some discussion of this is here, in which the following simple example is given in which both are used:
addEventListener('fetch', event => {
event.respondWith(
fetch(whatever).then(response => {
event.waitUntil(addThisToTheCache(response));
return response;
})
);
});
But couldn't this be written without a waitUntil
? As follows:
addEventListener('fetch', event => {
event.respondWith(
fetch(whatever).then(response => {
return addThisToTheCache(response).then(() => {
return response;
});
})
);
});
This will delay the browser processing & displaying the response by two seconds:
addEventListener('fetch', event => {
event.respondWith(async function() {
const response = await fetch(event.request);
await processResponseForTwoSeconds(response);
return response;
}());
});
This won't:
addEventListener('fetch', event => {
event.respondWith(async function () {
const response = await fetch(event.request);
event.waitUntil(processResponseForTwoSeconds(response));
return response;
}());
});
waitUntil
tells the service worker to stay alive for ongoing tasks, but does not delay the response.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With