Skip to content

Latest commit

 

History

History
31 lines (25 loc) · 1.02 KB

02-New-Async-Storage.md

File metadata and controls

31 lines (25 loc) · 1.02 KB
name order
Create a new asynchronous storage
2

Create a new asynchronous storage

There is a workaround (trickery) to work with asynchronous data storage. (Remember, StorageInterface.getValue should synchronously return a value)

The idea is to use the SelfUpdateStorageInterface interface to deliver the value when it finally arrived.

The IndexedDBStorage use this workaround.

Quick example

function myStorage<T>(): SelfUpdateStorageInterface<T> {
    const listeners: Array<{ key: string, listener: (newValue: T) => void }> = []
    const listenerFunction = (eventKey: string, newValue: T) => {
        listeners.filter(({ key }) => key === eventKey).forEach(({ listener }) => listener(newValue))
    }
    return {
        getValue(key: string): T | null {
            readRealStorageWithPromise(key).then((value) => listenerFunction(key, value))
            return null // Tell the store to use current decorated store value
        },
        // ... addListener, removeListener, setValue, deleteValue
    }
}