Cons of LocalStorage
LocalStorage is synchronous, each local storage operation you run will be one-at-a-time. For complex applications this is a big no-no as it'll slow down your app's runtime.
Pros of AsyncLocalStorage
AsyncLocalStorage is asynchronous, each local async storage operation you run will be multi-at-a-time. It'll speed up your app's runtime.
The AsyncLocalStorage JavaScript code is a facade that provides a clear JavaScript API, real Error objects, and non-multi functions. Each method in the API returns a Promise object.
Installation
async-local-storage is available on npm. It can be installed with the following command:
npm install --save @createnextapp/async-local-storage
async-local-storage is available on yarn as well. It can be installed with the following command:
yarn add @createnextapp/async-local-storage
Usage
Import
import AsyncLocalStorage from '@createnextapp/async-local-storage'
Store data
storeData = async () => {
try {
await AsyncLocalStorage.setItem('@key', 'value')
} catch(e) {
// error
}
}
Read data
readData = async () => {
let data
try {
data = await AsyncLocalStorage.getItem('@key')
} catch(e) {
// error
}
console.log(data)
/*
output:
value
*/
}
To learn more how to use async-local-storage:
Top comments (2)
Having skimmed the code I think your promise is just running the localStorage operations inside a wrapper? That just means that they are deferred a
tick
rather than truly Async and only one will happen one at a time and the read/write will happen all at once. This seems to just make it slower to read and write from localStorage. I would also argue that makes it hard to know which order things will happen in and what the state of a key actually is. Would be tricky if you mixed it with your own or library code that used localStorage directly.I love the documentation and the error message etc, I'm just not sure what the use case is as if I just wrote localStorage operations it would be faster and would block the main thread for the same amount of time.
great, thank you