0

I have two bits of code which i would expect to have worked in the same way however they dont - only one actually works and i cant figure out why.

Working one

 self.addEventListener('fetch',(e)=>{ e.respondWith(handleRequest(e.request)) }) async function handleRequest(req){ const res = await fetch(req); const cache = await caches.open(cacheName) if(res.ok){ // add the response to the caches and return the response await cache.put(req, res.clone()) return res; }else{ const res = cache.match(req) return res } } 

non working one

 self.addEventListener('fetch',(e)=>{ e.respondWith(async () => { const res = await fetch(e.request); const cache = await caches.open(cacheName) if(res.ok){ // add the response to the caches and return the response await cache.put(e.request, res.clone()) return res; }else{ const res = cache.match(e.request) return res } }) }) 

Can anyone see why this is?

3
  • in your async arrow function pass e.request` as a parameter as you did for normal function call. Commented Dec 20, 2020 at 13:41
  • But isnt it already in scope? Commented Dec 20, 2020 at 14:01
  • 1
    In the first example, you're passing the result of a function call. In the second, you're creating a functions and then passing a reference to it, but not actually calling it. Commented Dec 20, 2020 at 15:23

1 Answer 1

1

As stated by @Ouruborus you only passing the function reference instead of the function result. Compare this two example

console.log(() => { return 'test' }); 

vs.

console.log((() => { return 'test' })()); 

If you rewrite your code like this it should work:

self.addEventListener('fetch', (e) => { e.respondWith((async () => { const res = await fetch(e.request); const cache = await caches.open(cacheName) if (res.ok) { // add the response to the caches and return the response await cache.put(e.request, res.clone()) return res; } else { const res = cache.match(e.request) return res } })()); }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.