Skip to content

Commit

Permalink
refactor(server): don't use withResolvers()
Browse files Browse the repository at this point in the history
This was left over from an intermediate state when I thought I was going
to need promises and the ability to resolve them from outside. But I
don't need them, at least not for now.
  • Loading branch information
wincent committed Apr 18, 2024
1 parent 582309f commit 08a6979
Showing 1 changed file with 4 additions and 16 deletions.
20 changes: 4 additions & 16 deletions packages/server/src/Loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,7 @@ type BatchLoader<T, K> = (keys: Array<K>) => Promise<Array<T | Error>>;
export default class Loader<T, K = string> {
_cache: Map<K, T | Error>;
_loader: BatchLoader<T, K>;
_batch:
| Array<{key: K} & ReturnType<typeof Promise.withResolvers<T | Error>>>
| null;
_batch: Array<K> | null;

constructor(loader: BatchLoader<T, K>) {
this._cache = new Map();
Expand All @@ -30,27 +28,17 @@ export default class Loader<T, K = string> {
return new Promise((resolve) => {
if (this._batch) {
// A microtask has been scheduled but not started yet; add to it.
for (const key of keys) {
this._batch.push({
key,
...Promise.withResolvers(),
});
}
this._batch.push(...keys);
} else {
// Create a new batch.
this._batch = keys.map((key) => ({
key,
...Promise.withResolvers(),
}));
this._batch = [...keys];

// Schedule it.
queueMicrotask(async () => {
const batch = nullthrows(this._batch);
this._batch = null;

const uncached = batch.map(({key}) => key).filter((key) =>
!this._cache.has(key)
);
const uncached = batch.filter((key) => !this._cache.has(key));
if (uncached.length) {
const results = await this._loader(uncached);
if (results.length !== uncached.length) {
Expand Down

0 comments on commit 08a6979

Please sign in to comment.