Created
July 9, 2025 20:20
-
-
Save bmeck/c6d876612545324d1e8022aadf223e28 to your computer and use it in GitHub Desktop.
Why I want a sane await deferal and cache
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createHook } from 'node:async_hooks'; | |
let ticks = 0 | |
const asyncHook = createHook({ | |
before() { | |
ticks++ | |
}, | |
}); | |
asyncHook.enable(); | |
let normal = Promise.resolve('cloud_secret'); | |
let normal2 = Promise.resolve('cloud_secret'); | |
let val1 | |
let eager_defer = { | |
resolved: false, | |
async value() { | |
this.value = await Promise.resolve('cloud_secret') | |
this.resolved = true | |
return this.value | |
} | |
}; | |
let eager_defer2 = { | |
resolved: false, | |
async value() { | |
this.value = await Promise.resolve('cloud_secret') | |
this.resolved = true | |
return this.value | |
} | |
}; | |
async function process_normal() { | |
val1 = await Promise.all([normal, normal2]); | |
} | |
async function process_naive() { | |
val1 = [await normal, await normal2]; | |
} | |
async function process_deferred() { | |
val1 = [eager_defer.resolved ? eager_defer.value : eager_defer.value = await eager_defer.value(), eager_defer2.resolved ? eager_defer2.value : eager_defer2.value = await eager_defer2.value()]; | |
} | |
let runs = 1e4; | |
ticks = 0 | |
for (let i = 0; i < runs; i++) { | |
await null; | |
} | |
let ticks_from_bootstrap = ticks | |
async function run(fn) { | |
ticks = 0 | |
console.time(fn.name); | |
for (let i = 0; i < runs; i++) { | |
await fn(); | |
if (val1.length !== 2) throw new Error('invalid len') | |
if (val1[0] !== 'cloud_secret') throw new Error('[0]') | |
if (val1[1] !== 'cloud_secret') throw new Error('[1]') | |
} | |
console.timeEnd(fn.name); | |
console.log({ticks: ticks - ticks_from_bootstrap}) | |
} | |
await run(process_naive); | |
await run(process_normal); | |
await run(process_deferred); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment