服务工作者promise.then没有定义

时间:2017-10-20 02:09:56

标签: javascript promise es6-promise service-worker

我有这段代码:

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

它一直给我这个错误:

  

未捕获的TypeError:无法读取属性'然后'未定义的

它在这一行上捡起来:

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

以供参考:

这是函数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;

  });
}

doSomethingAsync功能:

function doSomethingAsync() {
      console.log("ASYNC LOL");
}

1 个答案:

答案 0 :(得分:2)

" 无法读取属性'然后'未定义的"告诉您doSomethingAsync()调用不返回具有then属性的对象。我想说doSomethingAsync必须返回Promise。 Promise对象在其原型(MDN)上有then方法,因此您可以调用它。试试这个

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

或只是

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