Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceWorker in sync event cant use waitUntil

I've got a correct ServiceWorker installation and I'm listening to the sync event with this code:

self.addEventListener("sync", function(event) {
  console.log("a sync catched");
  if (event.tag === "sync-newsletter") {
    console.log("is my sync");
    event.waitUntil(() => {
      return fetch("http://website.com/otherthings")
        .then(function(response) {
          console.log("ok, sent");
        });
    });
  }
});

And I correctly fire a sync event from the newsletter page with this code:

if ("serviceWorker" in navigator && "SyncManager" in window) {
  navigator.serviceWorker.ready.then(function(registration) {
    console.log("sw and sync available, sw ready");
    registration.sync.register("sync-newsletter").then(console.log("sync registered"));
    console.log("ended sync");
  });
} else {
  console.log("no newsletter for who dont have a sw and sync");
}

So on the console I got:

newsletter.js:85 sw and sync available, sw ready
newsletter.js:86 sync registered
newsletter.js:87 ended sync
serviceworker.js:79 a sync catched
serviceworker.js:81 is my sync

Then, debugging I see that doesn't enter in the event.waitUntil in the serviceworker, and goes directly at the end of the file.
What am I doing wrong?
Tried many times to empty cache, restart, reload, hard-reaload.

like image 422
lellefood Avatar asked Oct 29 '22 21:10

lellefood


1 Answers

waitUntil is expected to take a Promise instance, not a function that returns Promise.

self.addEventListener("sync", function(event) {
  console.log("a sync catched");
  if (event.tag === "sync-newsletter") {
    console.log("is my sync");
    event.waitUntil(fetch("http://website.com/otherthings")
      .then(function(response) {
        console.log("ok, sent");
      }));
  }
});
like image 126
NOtherDev Avatar answered Nov 08 '22 15:11

NOtherDev