0

に応え、私はこのエラーを取得しておいてください。サービスワーカーエラー:イベントはすでに

Uncaught (in promise) DOMException: Failed to execute 'respondWith' on 'FetchEvent': The event has already been responded to.

私は、非同期ものは機能をフェッチ中に点灯した場合、サービス労働者が自動的に応答するが、私はかなりこれをうまくできないことを知っていますビットはこのコードの違法行為者になります:

importScripts('cache-polyfill.js'); 

self.addEventListener('fetch', function(event) { 

    var location = self.location; 

    console.log("loc", location) 

    self.clients.matchAll({includeUncontrolled: true}).then(clients => { 
    for (const client of clients) { 
     const clientUrl = new URL(client.url); 
     console.log("SO", clientUrl); 
     if(clientUrl.searchParams.get("url") != undefined && clientUrl.searchParams.get("url") != '') { 
     location = client.url; 
     } 
    } 

    console.log("loc2", location) 

    var url = new URL(location).searchParams.get('url').toString(); 

    console.log(event.request.hostname); 
    var toRequest = event.request.url; 
    console.log("Req:", toRequest); 

    var parser2 = new URL(location); 
    var parser3 = new URL(url); 

    var parser = new URL(toRequest); 

    console.log("if",parser.host,parser2.host,parser.host === parser2.host); 
    if(parser.host === parser2.host) { 
    toRequest = toRequest.replace('https://booligoosh.github.io',parser3.protocol + '//' + parser3.host); 
    console.log("ifdone",toRequest); 
    } 

    console.log("toRequest:",toRequest); 

    event.respondWith(httpGet('https://cors-anywhere.herokuapp.com/' + toRequest)); 
    }); 
}); 

function httpGet(theUrl) { 
    /*var xmlHttp = new XMLHttpRequest(); 
    xmlHttp.open("GET", theUrl, false); // false for synchronous request 
    xmlHttp.send(null); 
    return xmlHttp.responseText;*/ 
    return(fetch(theUrl)); 
} 

助けていただければ幸いです。

答えて

2

event.respondWith()への呼び出しが最上位の約束の.then()句の中にあるということです。つまり、最上位の約束が解決した後で非同期に実行されるということです。期待している動作を得るには、fetchイベントハンドラの実行の一部として、event.respondWith()を同期して実行する必要があります。

あなたの約束の内部ロジックは従うことが少し難しいですので、私はあなたが達成しようとしているかを正確にわからないんだけど、一般的には、あなたがこのパターンに従うことができます。

self.addEventListerner('fetch', event => { 
    // Perform any synchronous checks to see whether you want to respond. 
    // E.g., check the value of event.request.url. 
    if (event.request.url.includes('something')) { 
    const promiseChain = doSomethingAsync() 
     .then(() => doSomethingAsyncThatReturnsAURL()) 
     .then(someUrl => fetch(someUrl)); 
     // Instead of fetch(), you could have called caches.match(), 
     // or anything else that returns a promise for a Response. 

    // Synchronously call event.respondWith(), passing in the 
    // async promise chain. 
    event.respondWith(promiseChain); 
    } 
}); 

です一般的なアイデア。 (約束をasync/awaitに置き換えた場合、コードはよりクリーンに見えます)

関連する問題