typicode / lowdb

Simple and fast JSON database
MIT License
21.56k stars 924 forks source link

Async update #596

Open tajnymag opened 2 months ago

tajnymag commented 2 months ago

Currently .update() awaits only the this.write() operation. It would be nice for it to also await the passed callback which mutates the state. Without the await, the persisted value could occur before the callback finishes its mutation.

// before
async update(fn: (data: T) => unknown): Promise<void> {
    fn(this.data)
    await this.write()
}

// after
async update(fn: (data: T) => unknown): Promise<void> {
    const result = fn(this.data);
    if (result instanceof Promise) {
      await result;
    }
    await this.write()
  }
kaaax0815 commented 2 months ago

I agree. Using something like

await Promise.resolve(fn(this.data))

or simply

await fn(this.data);

would be fairly simple.

If this is not wanted. At least do something like

type NotAsyncFunction<T> = T extends (...args: any[]) => Promise<any> ? never : T;

update<K>(fn: NotAsyncFunction<(data: T) => K>): Promise<void> {
  fn(this.data);
  await this.write()
}

to not allow async functions