Q:

Javascript service worker fetch only if the file exist in an object

I know this is not the best practice but i want to do it this way.
i want to wait for a file until it exist in an object, this is my code:
self.addEventListener('fetch', event => {
    event.respondWith(loadFile(event.request.url))
})
async function loadFile (url) {
    const name = fileName(url)
    if (localCache[name]) {
        return new Response(localCache[name])
    }
}

the problem here is when the file is not exist in localCache i get a failed request, and it keep requesting the same file until it exist in the localCache, every time it failed it show the fail request. 
what i want to do is something like this:
async function loadFile (url) {
    const name = fileName(url)
    let refreshId = setInterval(function() {
        if (localCache[name]) {
            return new Response(localCache[name])
            clearInterval(refreshId);
        }
    }, 3000);
}  

instead of showing that error and keep calling the same file, i want to call the function once and keep looping every 3 seconds until the file is added in localCache then return it.
there are a other code that add the files to localCache. but sometimes it takes some time to add all files to localCache.  

A:

You can try something like this:
async function loadFile (url) {
    const name = fileName(url)

    return new Promise((resolve, reject) => {
        let refreshId = setInterval(function() {
            if (localCache[name]) {
                resolve(new Response(localCache[name]));
                clearInterval(refreshId);
            }
        }, 3000);
    });
}

Or using await:
async function sleep(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}

async function loadFile (url) {
    const name = fileName(url)

    while (!localCache[name]) {
        await sleep(3000);
    }

    return new Response(localCache[name]);
}

