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

问题描述

使用基于 ionic 应用验证令牌的身份验证,将令牌存储在 localstorage 中需要时间来存储它正在移动到下一个状态是任何以异步方式在 localstorage 中设置值的解决方案

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 代码并行.它只是延迟作业,直到调用堆栈为空之后.它也不会处理来自浏览器上下文的其他事件,直到它也完成该工作.因此,例如,它仍然会阻止 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 13:42