I want to make a fetch
and store part of the result in a variable, in order to use that variable for subsequent requests to the Worker. I cannot make it work even with event.waitUntil
.
let githubStars
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event))
})
async function handleRequest(event) {
console.log(githubStars)
// await getGithubStars()
event.waitUntil(getGithubStars)
const response = await fetch(event.request)
return response
}
async function getGithubStars() {
if (githubStars) {
return
}
const response = await fetch('https://api.github.com/repos/instantpage/instant.page', {headers: {'User-Agent': 'instantpage'}})
const text = await response.text()
githubStars = JSON.parse(text).stargazers_count
}
Using async
works: the variable is undefined
on the first navigation (before calling getGithubStars
) then it’s the correct value on subsequent worker requests. Unfortunately event.waitUntil
doesn’t work.
Putting event.waitUntil
before or after event.respondWith
doesn’t work either.
Does someone know how to make this — setting a variable without blocking the first worker request — work?