typicode / lowdb

Simple and fast JSON database
MIT License
21.36k stars 921 forks source link

Async update #596

Open tajnymag opened 1 week ago

tajnymag commented 1 week 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()
  }