我是服务 worker 的新手。我正在接受 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!");
})
);
}
});
我知道有一种更好的方法可以使用服务工作线程进行嵌套获取,但我想知道我在这里做错了什么。
最佳答案
我还没有运行过这个,所以它可能需要一些调整,但尝试这样的事情。当前代码的问题是第一个获取 promise 链始终解析为响应。无论是在第一个 then
中,还是在第一个 catch
中,您都会返回 “呃哦,那完全失败了!”
的响应。 event.respondWith
接受该响应并愉快地按照它的方式进行。
外部 try/catch
存在于同步空间中,当 fetch 启动异步链时,因此您的代码将无法到达外部 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 - 嵌套获取服务工作线程中的响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50532300/