2015-10-15 32 views
6

我在我的服務勞動者有下列代碼中成功:看到,如果提出的要求,服務人員

self.addEventListener('fetch', function (event) { 
    var fetchPromise = fetch(event.request); 

    fetchPromise.then(function() { 
    // do something here 
    }); 

    event.respondWith(fetchPromise); 
}); 

然而,在做一些奇怪的東西,在開發者控制檯中,似乎被異步使腳本負荷而不是同步(在這種情況下是不好的)。

有什麼辦法當一個請求,而無需手動調用fetch(event.request)完成聽?

例如:

// This doesn't work 
self.addEventListener('fetch', function (event) { 
    event.request.then(function() { 
    // do something here 
    }); 
}); 
+0

你是什麼意思腳本加載異步?你在這個前端做什麼? – philnash

+0

@philnash:我覺得我是剛剛在瀑布困惑:http://i.imgur.com/S3eU293.png 我做了這一變化,並在網站的感知加載時間由35%加速(2.0秒 - > 1.3s)。仍然不知道爲什麼。 – callumacrae

回答

3

如果你想確保你的整個系列的動作進行響應返回到頁面之前,您應該與整個承諾鏈反應,而不僅僅是最初的承諾由提取返回。

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; 
    })); 
}); 
+0

是的,我並不擔心這一點。我實際上只是監控,而不是修改任何東西,所以它沒有任何區別。謝謝 :) – callumacrae