嵌套获取服务工作者中的响应

Bentaiba Miled Basma

我是服务工作者的新手。我正在接受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!");
    })
  );
});

我通过在 .git 文件中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 进行嵌套提取,但我想知道我在这里做错了什么。

危险

我没有运行过这个,所以它可能需要一些调整,但尝试这样的事情。您当前代码的问题在于第一个 fetch 承诺链总是解析为 Response。在第一个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!");
        })
    ); 
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章