0

I have this code:

self.addEventListener('fetch', function(event) {
const promiseChain = doSomethingAsync()
      .then(() => doSomethingAsyncThatReturnsAURL(event))
      .then(someUrl => fetch(someUrl));
event.respondWith(promiseChain);
});

It keeps giving me this error:

Uncaught TypeError: Cannot read property 'then' of undefined

It picks it up on this line:

.then(() => doSomethingAsyncThatReturnsAURL(event))

For reference:

Here is the function doSomethingAsyncThatReturnsAURL:

function doSomethingAsyncThatReturnsAURL(event) {
  var location = self.location;

  console.log("loc", location)

  self.clients.matchAll({includeUncontrolled: true}).then(clients => {
    for (const client of clients) {
      const clientUrl = new URL(client.url);
      console.log("SO", clientUrl);
      if(clientUrl.searchParams.get("url") != undefined && clientUrl.searchParams.get("url") != '') {
        location = client.url;
      }
    }

  console.log("loc2", location)

  var url = new URL(location).searchParams.get('url').toString();

  console.log(event.request.hostname);
  var toRequest = event.request.url;
  console.log("Req:", toRequest);

  var parser2 = new URL(location);
  var parser3 = new URL(url);

  var parser = new URL(toRequest);

  console.log("if",parser.host,parser2.host,parser.host === parser2.host);
  if(parser.host === parser2.host) {
    toRequest = toRequest.replace('https://booligoosh.github.io',parser3.protocol + '//' +  parser3.host);
    console.log("ifdone",toRequest);
  }

  console.log("toRequest:",toRequest);

  var finalResult = 'https://cors-anywhere.herokuapp.com/' + toRequest;

  return finalResult;

  });
}

And the doSomethingAsync function:

function doSomethingAsync() {
      console.log("ASYNC LOL");
}
Ethan
  • 3,410
  • 1
  • 28
  • 49

1 Answers1

2

"Cannot read property 'then' of undefined" tells you that doSomethingAsync() call does not return an object with then property. I would to say that doSomethingAsync must return Promise. The Promise object has then method on its prototype (MDN), so you can call it. Try this

function doSomethingAsync() {
  return new Promise(resolve => {
    console.log("ASYNC LOL");
    resolve();
  })
}

or just

function doSomethingAsync() {
  console.log("ASYNC LOL");
  return Promise.resolve();
}
dhilt
  • 18,707
  • 8
  • 70
  • 85