将async/await与responsdWith一起使用



我有两段代码,我希望它们以相同的方式工作,但它们没有——只有一段真正工作,我不知道为什么。

工作一个


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
}
}

不工作的一个


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
}
})

})

有人知道为什么吗?

正如@Ouruborus所说,您只传递函数引用,而不是函数结果。比较这两个示例

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

与。

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

如果你这样重写你的代码,它应该可以工作:

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
}
})());
});

最新更新