2017-09-14 43 views
1

我在看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); 
      }) 
      ); 
}); 

据上找到任何东西,因为我读的取()的文档,没有超时功能,所以我的假设是超时函数被添加到util.js中,这是从来没有在演示文稿中显示的...任何人都可以证实这一点?有没有人有关于如何实施的想法?

回答

1

未来:

它的到来。

Jake Archibald's commentwhatwg/fetch未来的语法为:

使用abort语法,你就能够做到:

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; 
// … 

如果你只是想超时请求,而不是响应,请添加:

clearTimeout(timeoutId); 
// … 

而且从另一个评论:

边缘&火狐已经在实施。 Chrome将很快启动。

现在:

如果你想尝试,现在的工作,最明智的方法是使用this module的解决方案。

它允许您使用的语法,如:

return fetch('/path', {timeout: 500}).then(function() { 
    // successful fetch 
}).catch(function(error) { 
    // network request failed/timeout 
}) 
+0

我会尝试了这一点。谢谢 – JoSSte