Diffinery

homeflare/celldpublic

30 lines · 1.1 KBRaw History
1// Exercises the async-op layer: a DO that awaits a timer and an outbound fetch.
2// Both need a real event loop — under a synchronous busy-loop they hang forever.
3// Plain DO code: runs identically on Cloudflare.
4export class A {
5 constructor(state, env) { this.state = state; }
6 async fetch(request) {
7 const u = new URL(request.url);
8 if (u.pathname === "/timer") {
9 const t0 = Date.now();
10 await new Promise((r) => setTimeout(r, 30));
11 return new Response(JSON.stringify({ waitedMs: Date.now() - t0 }));
12 }
13 if (u.pathname === "/fetch") {
14 const resp = await fetch(u.searchParams.get("url"));
15 const body = await resp.text();
16 return new Response(JSON.stringify({ status: resp.status, len: body.length }));
17 }
18 // combined: await a timer, then read-modify-write persistent state
19 await new Promise((r) => setTimeout(r, 5));
20 let n = (await this.state.storage.get("n")) ?? 0;
21 n++;
22 await this.state.storage.put("n", n);
23 return new Response(JSON.stringify({ n }));
24 }
25}
26export default {
27 async fetch(request, env) {
28 return env.A.get(env.A.idFromName("a")).fetch(request);
29 }
30};