Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is any solution to do localstorage setItem in asynchronous way in javascript

Using ionic app validating token based auth, Storing the token in localstorage it is taking time to store in between it is moving to next state is any solution to do asynchronous way to set value in localstorage

window.localStorage.setItem('ChemistloggedInUser', JSON.stringify(data))
like image 962
koneri ranjith kumar Avatar asked Mar 21 '17 07:03

koneri ranjith kumar


People also ask

Is localStorage setItem asynchronous?

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.

Is writing to localStorage async?

Nope, all localStorage calls are synchronous.

Is sessionStorage setItem synchronous?

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.


1 Answers

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.resolve().then(function () {
            localStorage.setItem(key, value);
        });
    },
    getItem: function (key) {
        return Promise.resolve().then(function () {
            return localStorage.getItem(key);
        });
    }
};

// Demo
const data = Date.now() % 1000;
asyncLocalStorage.setItem('mykey', data).then(function () {
    return asyncLocalStorage.getItem('mykey');
}).then(function (value) {
    console.log('Value has been set to:', value);
});
console.log('waiting for value to become ' + data + 
            '. Current value: ', localStorage.getItem('mykey'));

See it run on repl.it, as SO snippets do not allow the use of localStorage.

With the newer async/await syntax, this asyncLocalStorage can be written as:

const asyncLocalStorage = {
    setItem: async function (key, value) {
        await null;
        return localStorage.setItem(key, value);
    },
    getItem: async function (key) {
        await null;
        return localStorage.getItem(key);
    }
};

repl.it

Note about "asynchronous"

Be aware that, although the above let's you continue with other code immediately, once that code has been executed, the job of accessing local storage will kick in and will use the same thread. So it is not like it runs in the background, in parallel with your own JS code. It just delays the job until after the call stack is empty. It also does not process other events from the browser context until it also finishes that job. So, for instance, it will still block the GUI.

If you need the access to happen in parallel, then you're out of luck with localStorage. For instance, that API is not available in Web Workers, which would otherwise have been a possible way out.

You could look into the IndexedDB API as an alternative. But:

  • It is much more complicated to work with
  • Although it has an asynchronous interface, several browser implementations still block the DOM (so the above comments apply)
  • IndexedDB can be used by a Web Worker, which gives better parallelism, but makes it even more complex to implement.
like image 116
trincot Avatar answered Oct 21 '22 00:10

trincot