Returning KV values from Cloudflare Workers

If you haven't worked much with async javascript functions, this is not the most obvious thing in the world, and it's not covered in any of their examples (that I could see). So, here we go!

First, definitions!

The thing about workers, though, is that they are mostly javascript but ... not 100% the same. There's some quirks. In this case, there are two things to know:

For example, this is a whole worker to get a date value of out KV:

addEventListener("fetch", event => {
  event.respondWith(serverResponse(event));
});

async function serverResponse(event) {
  const date = await mynamespace.get('date');
  return new Response(date);
}

mynamespace is the variable I bound to my KV namespace, so I can access all the values in that namespace.

Pro Tip: If you get the error "date is not defined" and you've triple-checked the name of the key? Make sure you've put it in quotes. mynamespace.get(date) does not work. Ask me how many times I've made that mistake 😂

And if you want to return two or more KV values with a single call? Here you go:

addEventListener("fetch", event => {
  event.respondWith(serverResponse(event));
});

async function serverResponse(event) {
    // get the values
    const nutValue = await mynamespace.get('nut');
    const boltValue = await mynamespace.get('bolt');
    const widget = {
        nut: nutValue,
        bolt: boltValue;
    }
    // convert to a string
    const json = JSON.stringify(widget, null, 2);
    // send it back
    return new Response(json);
}