【问题标题】:Seeing if a request succeeds from within a service worker查看服务工作者中的请求是否成功
【发布时间】:2016-01-13 18:19:16
【问题描述】:

我的服务人员中有以下代码:

self.addEventListener('fetch', function (event) {
  var fetchPromise = fetch(event.request);

  fetchPromise.then(function () {
    // do something here
  });

  event.respondWith(fetchPromise);
});

但是,它在开发控制台中做了一些奇怪的事情,并且似乎使脚本异步加载而不是同步加载(在这种情况下这很糟糕)。

有没有什么方法可以在不手动调用fetch(event.request) 的情况下监听请求何时完成?

例如:

// This doesn't work
self.addEventListener('fetch', function (event) {
  event.request.then(function () {
    // do something here
  });
});

【问题讨论】:

  • 脚本正在异步加载是什么意思?你在前端做什么?
  • @philnash:我想我只是被瀑布弄糊涂了:i.imgur.com/S3eU293.png 我做了这个改变,网站的感知加载时间加快了 35%(2.0s -> 1.3s) .仍然不知道为什么。

标签: javascript service-worker fetch-api


【解决方案1】:

如果您想确保在响应返回到页面之前执行您的整个系列操作,您应该使用整个 Promise 链进行响应,而不仅仅是 fetch 返回的初始 Promise。

self.addEventListener('fetch', function(event) {
  event.respondWith(fetch(event.request).then(function(response) {
    // The fetch() is complete and response is available now.
    // response.ok will be true if the HTTP response code is 2xx
    // Make sure you return response at the end!
    return response;
  }).catch(function(error) {
    // This will be triggered if the initial fetch() fails,
    // e.g. due to network connectivity. Or if you throw an exception
    // elsewhere in your promise chain.
    return error;
  }));
});

【讨论】:

  • 是的,我不担心这个。我实际上只是在监控,没有修改任何东西,所以它并没有真正产生任何影响。谢谢:)
猜你喜欢
  • 2016-02-23
  • 2019-11-29
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
  • 2020-02-15
  • 2018-01-15
  • 2016-05-18
  • 2021-08-07
相关资源
最近更新 更多