Fetching and setting a variable after sending the main response

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? :pray:

Not sure if it helps out

const response = await fetch('https://api.github.com/repos/instantpage/instant.page', {headers: {'User-Agent': 'instantpage'}})
  let response_obj = await response.json()
  githubStars = response_obj.stargazers_count

I fixed it.

event.waitUntil(getGithubStars)

Should be:

event.waitUntil(getGithubStars())

With parentheses.

2 Likes

Note that this only works as long as the worker is running. In my testing, they tend to get stopped within 1 minute of no traffic when deployed, meaning they forget about stuff like closures (like your githubStars). You can use the Cache API if you need to keep stuff around more reliably Cache · Cloudflare Workers docs