diff --git a/asyncforge.js b/asyncforge.js index c8dc208..28863cd 100644 --- a/asyncforge.js +++ b/asyncforge.js @@ -43,10 +43,22 @@ function memo (name) { } get.set = set + get.key = sym return get } +function setAll (memos) { + let store = asyncLocalStorage.getStore() + store = Object.create(store) + const keys = Object.getOwnPropertySymbols(memos) + for (const key of keys) { + store[key] = memos[key] + } + asyncLocalStorage.enterWith(store) +} + module.exports.start = start module.exports.forge = forge module.exports.memo = memo +module.exports.setAll = setAll diff --git a/test/setall.test.js b/test/setall.test.js new file mode 100644 index 0000000..33828d2 --- /dev/null +++ b/test/setall.test.js @@ -0,0 +1,23 @@ +'use strict' + +const { test } = require('node:test') +const { start, memo, setAll } = require('../') +const assert = require('node:assert/strict') + +test('setAll memos', async (t) => { + const a = memo() + const b = memo() + const c = memo() + + start() + + setAll({ + [a.key]: 1, + [b.key]: 2, + [c.key]: 3 + }) + + assert.equal(a(), 1) + assert.equal(b(), 2) + assert.equal(c(), 3) +})