IndexedDB之并發(fā)問(wèn)題(Concurrency Issues)
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在網(wǎng)頁(yè)里是一個(gè)異步接口,但是仍然會(huì)有并發(fā)問(wèn)題。假如相同的頁(yè)面同時(shí)在兩個(gè)不同的瀏覽器頁(yè)簽打開(kāi),很有可能在一個(gè)準(zhǔn)備好之前另一個(gè)正在嘗試更新。成問(wèn)題的操作是在把數(shù)據(jù)庫(kù)設(shè)置成要給新版本的時(shí)候,因此只有當(dāng)瀏覽器上只有一個(gè)正在使用數(shù)據(jù)庫(kù)的頁(yè)簽打開(kāi)時(shí),setVersion()的調(diào)用才能被完成。
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:
翻譯:
當(dāng)你第一次打開(kāi)數(shù)據(jù)庫(kù)的時(shí)候,綁定一個(gè)onversionchange事件是很重要的。當(dāng)其相同域名的其他頁(yè)簽調(diào)用setVersion()方法時(shí),該事件會(huì)被執(zhí)行。對(duì)該事件最好的響應(yīng)是關(guān)閉數(shù)據(jù)庫(kù),一遍版本更新能被完成。例如:
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.
翻譯:
每次成功的打開(kāi)數(shù)據(jù)庫(kù)都應(yīng)該給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:
翻譯:
當(dāng)你調(diào)用方法setVersion()時(shí),給請(qǐng)求綁定一個(gè)onblocked事件也很重要。當(dāng)其他頁(yè)面讓數(shù)據(jù)庫(kù)是開(kāi)著,同時(shí)正試圖更新版本的時(shí)候,該事件發(fā)生。在那種情況下,你可能想要告知用戶在嘗試setVersion()方法之前,關(guān)閉所有其他的頁(yè)面。例如:
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被調(diào)用的。
By always assigning these event handlers, you will ensure your web application will be able to better handle concurrency issues related to IndexedDB.
翻譯:
通過(guò)上述這些事件的處理,你能確保你的網(wǎng)頁(yè)應(yīng)用能夠更好的處理跟IndexDB相關(guān)的并發(fā)問(wèn)題。