cal*_*rae 6 javascript service-worker fetch-api
我的服务工作者中有以下代码:
self.addEventListener('fetch', function (event) {
var fetchPromise = fetch(event.request);
fetchPromise.then(function () {
// do something here
});
event.respondWith(fetchPromise);
});
Run Code Online (Sandbox Code Playgroud)
但是,它在开发控制台中做了一些奇怪的事情,似乎是使脚本异步加载而不是同步(在这种情况下是坏的).
有没有办法在没有fetch(event.request)手动调用的情况下完成请求?
例如:
// This doesn't work
self.addEventListener('fetch', function (event) {
event.request.then(function () {
// do something here
});
});
Run Code Online (Sandbox Code Playgroud)
如果您想确保在响应返回到页面之前执行整个系列的操作,您应该使用整个 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;
}));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
85 次 |
| 最近记录: |