DenoDDeno
Powered by
kuboonK
Deno•8mo ago•
3 replies
kuboon

Can I use deno KV in worker?

It looks work, but does not persist at all.
See my sample code below.

Q1. why "key1" is not listed in my worker?
Q2. why "key2" always 1?


deno -v
deno 2.4.4

deno run --allow-read=. kvTest.ts
I am NOT in a web worker
{ key: [ "key1" ], value: 8, versionstamp: "00000000000000e00000" }
I am in a web worker
{ key: [ "key2" ], value: 1, versionstamp: "00000000000000090000" }


const kv = await Deno.openKv();
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
  console.log('I am in a web worker');
  await increment("key2")
  await listAll();
} else {
  console.log('I am NOT in a web worker');
  await increment("key1")
  await listAll();
  new Worker(import.meta.url, { type: "module" });
}

async function increment(key: string) {
  const current = await kv.get([key]);
  await kv.atomic().check(current).set([key], (current.value as number ?? 0) + 1).commit();
}
async function listAll(){
  for await (const entry of kv.list({ prefix: [] })) {
    console.log(entry);
  }
}
const kv = await Deno.openKv();
if (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope) {
  console.log('I am in a web worker');
  await increment("key2")
  await listAll();
} else {
  console.log('I am NOT in a web worker');
  await increment("key1")
  await listAll();
  new Worker(import.meta.url, { type: "module" });
}

async function increment(key: string) {
  const current = await kv.get([key]);
  await kv.atomic().check(current).set([key], (current.value as number ?? 0) + 1).commit();
}
async function listAll(){
  for await (const entry of kv.list({ prefix: [] })) {
    console.log(entry);
  }
}
Deno banner
DenoJoin
Chat about Deno, a modern runtime for JavaScript and TypeScript.
20,934Members
Resources

Similar Threads

Was this page helpful?

Continue the conversation

Join the Discord to ask follow-up questions and connect with the community

DenoD

Deno

Chat about Deno, a modern runtime for JavaScript and TypeScript.

20,934 Members

Join

Similar Threads

Dates in Deno KV
vwkdVvwkd / help
8mo ago
In memory Deno Kv
didiercrunchDdidiercrunch / help
3y ago
Using deno_kv in rust?
Testersen™TTestersen™ / help
11mo ago