IndexedDB之并发问题(Concurrency Issues)

欢欢欢欢 发表于 2018-3-2 13:29

While IndexedDB is an asynchronous API inside of a web page, there are still concurrency issues. If the same web page is open in two different browser tabs at the same time, it’s possible that one may attempt to upgrade the database before the other is ready. The problematic operation is in setting the database to a new version, and so calls to setVersion() can be completed only when there is just one tab in the browser using the database.

翻译:

虽然IndexDB在网页里是一个异步接口,但是仍然会有并发问题。假如相同的页面同时在两个不同的浏览器页签打开,很有可能在一个准备好之前另一个正在尝试更新。成问题的操作是在把数据库设置成要给新版本的时候,因此只有当浏览器上只有一个正在使用数据库的页签打开时,setVersion()的调用才能被完成。

When you first open a database, it’s important to assign an onversionchange event handler. This callback is executed when another tab from the same origin calls setVersion(). The best response to this event is to immediately close the database so that the version upgrade can be completed. For example:

翻译:

当你第一次打开数据库的时候,绑定一个onversionchange事件是很重要的。当其相同域名的其他页签调用setVersion()方法时,该事件会被执行。对该事件最好的响应是关闭数据库,一遍版本更新能被完成。例如:

var request, database; request = indexedDB.open(“admin”);

request.onsuccess = function(event){

database = event.target.result;

database.onversionchange = function(){ database.close(); };

};

You should assign onversionchange after every successful opening of a database.

翻译:

每次成功的打开数据库都应该给onversionchange事件赋值。

When you are calling setVersion(), it’s also important to assign an onblocked event handler to the request. This event handler executes when another tab has the database open while you’re trying to update the version. In that case, you may want to inform the user to close all other tabs before attempting to retry setVersion(). For example:

翻译:

当你调用方法setVersion()时,给请求绑定一个onblocked事件也很重要。当其他页面让数据库是开着,同时正试图更新版本的时候,该事件发生。在那种情况下,你可能想要告知用户在尝试setVersion()方法之前,关闭所有其他的页面。例如:

var request = database.setVersion(“2.0”);

request.onblocked = function(){ alert(“Please close all other tabs and try again.”); };

request.onsuccess = function(){ //handle success, continue on };

Remember, onversionchange will have been called in the other tab(s) as well.

翻译:

切记,onversionchange事件是在其他tab被调用的。

By always assigning these event handlers, you will ensure your web application will be able to better handle concurrency issues related to IndexedDB.

翻译:

通过上述这些事件的处理,你能确保你的网页应用能够更好的处理跟IndexDB相关的并发问题。