javascript - 嵌套获取服务工作者中的响应
问题描述
我是服务人员的新手。我正在接受 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 进行嵌套提取,但我想知道我在这里做错了什么。
解决方案
我没有运行它,所以它可能需要一些调整,但试试这样的。您当前代码的问题是第一个获取承诺链总是解析为响应。在第一个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!");
})
);
});
推荐阅读
- javascript - 从 Node Express 服务器重定向到客户端反应应用程序
- wordpress - 将 OR 条件与 facetwp 构面一起使用
- flutter - 如何生成比前一个数字多一位的数字?
- scala - 在 HashMap 中缓存函数值
- rust - Rust 命令行历史就像在终端中一样
- php - 使用 curl 登录 PHP 站点
- flutter - 在 Flutter 项目的项目目录中找不到 `Podfile'
- r - 使用 Parallelly 包在 R 中运行并行代码时如何解决连接问题?
- javascript - 点击没有在 jquery 中的锚标记上工作
- scala - 线程“主”org.apache.spark.sql.AnalysisException 中的异常:无法解析给定输入列的“id”:[0、33、385、Will];