首页 > 解决方案 > 嵌套获取服务工作者中的响应

问题描述

我是服务人员的新手。我正在接受 Udacity 提供的移动网络专家培训,为此我正在使用 google-chrome。我想从网络获取响应,如果它返回 404 作为状态,我也会从网络获取另一个响应。这是一个只能从网络获取一次的代码。此代码完美运行:

self.addEventListener('fetch', function(event) {
  event.respondWith(
    fetch(event.request).then(function(response) {
      if (response.status === 404) {
        return new Response("Whoops, not found");
      }
      return response;
    }).catch(function() {
      return new Response("Uh oh, that totally failed!");
    })
  );
});

response.status === 404以相同的方式在try/catch. 更新后的代码如下:

self.addEventListener('fetch', function(event) {
 try {
  event.respondWith(
    fetch(event.request).then(function(response) {
      if (response.status === 404) {
        throw (Error);
      }
      return response;
    }).catch(function() {
      return new Response("Uh oh, that totally failed!");
    })
  );
 } catch (Error) {
   event.respondWith(
    fetch('/imgs/dr-evil.gif').then(function(response) {
      if (response.status === 404) {
        return new Response('couldn\'t fetch twice');
      }
      return response;
    }).catch(function() {
      return new Response("Uh oh, that totally failed twice!");
    })
  );
 }
});

我知道有一种更好的方法可以使用 service-worker 进行嵌套提取,但我想知道我在这里做错了什么。

标签: javascriptgoogle-chromeservice-worker

解决方案


我没有运行它,所以它可能需要一些调整,但试试这样的。您当前代码的问题是第一个获取承诺链总是解析为响应。在第一个then或第一个catch中,您返回的响应为"Uh oh, that totally failed!". 接受了这个event.respondWith回应,并愉快地沿着它的方式前进。

外部try/catch存在于同步空间中,当获取启动异步链时,您的代码将无法到达外部捕获,因为它不在获取的执行上下文中。

如果 service worker 和 async/await 的兼容性相同(我不知道),您可能想看看它,因为这将是一种更友好的方式来构建您的代码。

self.addEventListener('fetch', function(event) {
    event.respondWith(
        fetch(event.request).then(function(response) {
            if (response.status === 404) {
                throw (Error);
            }
            return response;
        }).catch(function() {
            return fetch('/imgs/dr-evil.gif').then(function(response) {
                if (response.status === 404) {
                    throw (Error);
                }
                return response;
            })
        }).catch(function() {
            return new Response("Uh oh, that totally failed twice!");
        })
    ); 
});

推荐阅读