23 lines
925 B
TypeScript
23 lines
925 B
TypeScript
/** Includes child writes registered by tasks that are already running. */
|
|
export class DatabaseBackgroundWork {
|
|
private pending = new Set<Promise<unknown>>()
|
|
|
|
track<T>(task: Promise<T>): Promise<T> {
|
|
this.pending.add(task)
|
|
void task.then(() => this.pending.delete(task), () => this.pending.delete(task))
|
|
return task
|
|
}
|
|
|
|
async drain(timeoutMs = 30_000): Promise<void> {
|
|
let timer: ReturnType<typeof setTimeout> | undefined
|
|
const timeout = new Promise<never>((_, reject) => {
|
|
timer = setTimeout(() => reject(new Error("Не удалось дождаться фоновых записей; операция с базой отменена")), timeoutMs)
|
|
})
|
|
try {
|
|
while (this.pending.size) await Promise.race([Promise.allSettled([...this.pending]), timeout])
|
|
} finally { if (timer) clearTimeout(timer) }
|
|
}
|
|
}
|
|
|
|
export const databaseBackgroundWork = new DatabaseBackgroundWork()
|