我正在观看Steve Sanderson's NDC presentation on up-and-coming web features,并将他的缓存示例视为我正在开发的应用程序的主要候选者。我无法找到代码,因此我已尽可能地将其从Youtube视频中输入。
不幸的是,它在Chrome中不起作用(这也是他在演示中使用的内容)它失败了Uncaught TypeError: fetch(...).then(...).timeout is not a function
at self.addEventListener.event
。
我浏览了Steve's Github,没有发现这一点,也没有在NDC会议页面上找到任何内容
//inspiration:
// https://www.youtube.com/watch?v=MiLAE6HMr10
//self.importScripts('scripts/util.js');
console.log('Service Worker script running');
self.addEventListener('install', event => {
console.log('WORKER: installing');
const urlsToCache = ['/ServiceWorkerExperiment/', '/ServiceWorkerExperiment/scripts/page.js'];
caches.delete('mycache');
event.waitUntil(
caches.open('mycache')
.then(cache => cache.addAll(urlsToCache))
.then(_ => self.skipWaiting())
);
});
self.addEventListener('fetch', event => {
console.log(`WORKER: Intercepted request for ${event.request.url}`);
if (event.request.method !== 'GET') {
return;
}
event.respondWith(
fetch(event.request)
.then(networkResponse => {
console.log(`WORKER: Updating cached data for ${event.request.url}`);
var responseClone = networkResponse.clone();
caches.open('mycache').then(cache => cache.put(event.request, responseClone));
return networkResponse;
})
//if network fails or is too slow, return cached data
//reference for this code: https://youtu.be/MiLAE6HMr10?t=1003
.timeout(200)
.catch(_ => {
console.log(`WORKER: Serving ${event.request.url} from CACHE`);
return caches.match(event.request);
})
);
});
就我读取fetch()文档而言,没有超时功能,所以我的假设是在util.js中添加了超时功能,这在演示文稿中从未显示过......任何人都可以确认吗?有没有人知道如何实现这个?
答案 0 :(得分:1)
<强>未来:强>
它来了。
根据SELECT COALESCE(client_nmbr, company_nmbr) all_nmbr
FROM General
LEFT JOIN Clients ON client_id = all_id
LEFT JOIN Companies ON company_id = all_id
ORDER BY all_id
上的Jake Archibald's comment,未来的语法将是:
使用中止语法,您将能够:
whatwg/fetch
如果您只想超时请求而不是响应,请添加:
const controller = new AbortController();
const signal = controller.signal;
const fetchPromise = fetch(url, {signal});
// 5 second timeout:
const timeoutId = setTimeout(() => controller.abort(), 5000);
const response = await fetchPromise;
// …
另一条评论:
Edge&amp; Firefox已经在实施。 Chrome很快就会启动。
立即强>
如果您想尝试现在有效的解决方案,最明智的方法是使用this module。
它允许您使用如下语法:
clearTimeout(timeoutId);
// …