atomic operation on window.localStorage

回眸只為那壹抹淺笑 提交于 2020-01-05 06:15:42

问题


Is this possible to do when setting 2 or more values? I am using phonegap and concerned that the user could kill the app while before it finishes setting both values.

I realize that I could use W3C web sql with a transaction but didn't want the overkill of sql for what I am doing.


回答1:


By default, no, there is no locking mechanism. However, you may want to check out this question also, and this site that it references. You would be better off with a SQL transaction if persistence of those values in an atomic fashion is vital to your program.




回答2:


Protect the writes:

localStorage.setItem("writing", "1");

localStorage.setItem("k1", "v1");
localStorage.setItem("k2", "v2");
...

localStorage.removeItem("writing");

Then, when loading the DB:

if (localStorage.writing != undefined)
{
    treat the DB as corrupted
}


来源:https://stackoverflow.com/questions/14330477/atomic-operation-on-window-localstorage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!