Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using both respondWith and waitUntil in a fetch event

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;
      });
    })
  );
});
like image 426
drmrbrewer Avatar asked Nov 14 '17 09:11

drmrbrewer


1 Answers

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.

like image 103
JaffaTheCake Avatar answered Oct 06 '22 03:10

JaffaTheCake