在javascript中以异步方式执行localstorage setItem的任何解决方案 [英] Is any solution to do localstorage setItem in asynchronous way in javascript

查看:1564
本文介绍了在javascript中以异步方式执行localstorage setItem的任何解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用离子应用程序验证基于令牌的身份验证,将令牌存储在本地存储中,在它们之间转移到下一个状态之间需要花费时间,这是任何以异步方式在本地存储中设置值的解决方案

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))

推荐答案

localStorage是同步API.您可以使用Promise对象延迟setItem方法的执行,从而为它们提供异步行为:

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'));

看到它在 repl.it 上运行,因为SO片段不允许使用localStorage.

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

使用更新的async/await语法,此asyncLocalStorage可以写为:

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

请注意,尽管以上内容使您可以立即继续执行其他代码,但是一旦执行了该代码,访问本地存储的工作就会启动并使用同一线程.因此,它不像是在后台运行,与您自己的JS代码进行 parallel .它只是延迟作业,直到调用堆栈为空为止.在完成该工作之前,它也不会处理来自浏览器上下文的其他事件.因此,例如,它仍然会阻止GUI.

Be aware that, although the above lets 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.

如果您需要并行访问,那么localStorage会让您不走运.例如,该API在Web Workers中不可用,否则可能是一种解决方法.

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.

您可以将 IndexedDB API 选择.但是:

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

  • 使用它要复杂得多
  • 尽管它具有异步接口,但几种浏览器实现仍会阻止DOM (因此,上述注释适用)
  • IndexedDB可由Web Worker使用,它提供了更好的并行性,但实现起来更加复杂.
  • 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.

这篇关于在javascript中以异步方式执行localstorage setItem的任何解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆