Search code examples
javascriptfunctional-programmingbrowser-cache

Why "Failed to execute 'delete' on 'Cache': Illegal invocation" when cachel.delete is assigned to variable?


I'm trying to pass cache.delete native function as an argument in order to make my code more easily testable.

But when I do this:

const cacheDeleteFunction = cache.delete;
await cacheDeleteFunction(request);

it fails with Failed to execute 'delete' on 'Cache': Illegal invocation error.

Same code, but with a direct call to await cache.delete(request) works.

Also, if I do this:

const cacheDeleteFunction = (x) => cache.delete(x);
await cacheDeleteFunction(request);

then it also works!

I've tried playing with .apply() and .call() but they didn't make any difference.

(async () => {
    const cache = await caches.open('1');
    try {
        await cache.add(new Request('?apple'));
        await cache.add(new Request('?google'));
    } catch (e) {}
    const keys = await cache.keys();
    for (const request of keys) {
        if (request.url.includes('apple')) {
            // Failed to execute 'delete' on 'Cache': Illegal invocation
            // const cacheDeleteFunction = cache.delete;
            // await cacheDeleteFunction(request);


            // Works
            await cache.delete(request);

            // Also works
            // const cacheDeleteFunction = (x) => cache.delete(x);
            // await cacheDeleteFunction(request);
        }
    }
})();

What am I missing? Why const cacheDeleteFunction = cache.delete; doesn't work?

Related issue: https://github.com/noahjohn9259/react-clear-cache/pull/36/files


Solution

  • The issue is probably because the delete function references the "this". So when you get a reference to it without using bind the this would be undefined. so what you need to do is doing:

    const deleteFunction = cache.delete.bind(cache);