localStorage is a synchronous API. You could defer the setItem method execution with the Promise object, giving them an asynchronous behaviour: const asyncLocalStorage = { setItem: function (key, value) { return Promise.
To create a key-value pair inside the sessionStorage object, you can use the setItem method, similar to the localStorage object. Just like localStorage , sessionStorage is also a synchronous API, so you can be sure that you'll immediately have access to whatever values you're storing.
HTML5 local storage is a component of the Web storage application programming interface. It is a method by which Web pages locally store named key/value pairs inside a client's Web browser.
Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
Nope, all localStorage
calls are synchronous.
Actually. web storage is no longer part of the HTML5 core standard, it's been split off.
The relevant (draft) specification can be found here and the one thing you'll notice is that it doesn't mention synchronous or asynchronous anywhere.
However, analysis of the text would suggest that it must be synchronous (my bold):
The setItem(key, value) method must first check if a key/value pair with the given key already exists in the list associated with the object.
If it does not, then a new key/value pair must be added to the list, with the given key and with its value set to value.
If the given key does exist in the list, and its value is not equal to value, then it must have its value updated to value. If its previous value is equal to value, then the method must do nothing.
In standards, words like must
, shall
and may
carry very specific meanings. That fact that it's talking about what the method must do means that the method itself must do it, not defer it to some later time.
This also defers to common sense as well. If the setItem
were asynchronous, it would be possible to set an item to a specific value then immediately retrieve it, getting its previous value.
There is a note at the bottom of the storage interface section which hints at the possibility of asynchronous behaviour:
This specification does not require that the above methods wait until the data has been physically written to disk. Only consistency in what different scripts accessing the same underlying list of key/value pairs see is required.
However, that's only in terms of what's written to long-term storage. The last sentence mandates that scripts accessing the same storage object are required to see things synchronously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With