我在用indexedDB做实验。现在一切都像是异步的,这对我的大脑有很大的伤害。
我创建了这样一个对象:
var application = {};
application.indexedDB = {};
application.indexedDB.db = null;
application.indexedDB.open = function() {
var dbName = "application";
var dbVersion = 1;
var openRequest = indexedDB.open(dbName, dbVersion);
openRequest.onupgradeneeded = function(e) {
console.log("Upgrading your DB (" + dbName + ", v" + dbVersion + ")...");
var thisDB = e.target.result;
if (!thisDB.objectStoreNames.contains("journal")) {
thisDB.createObjectStore(
"journal",
{keyPath: "id"}
);
}
}
openRequest.onsuccess = function(e) {
console.log("Opened DB (" + dbName + ", v" + dbVersion + ")");
application.indexedDB.db = e.target.result;
}
openRequest.onerror = function(e) {
console.log("Error");
console.dir(e);
}
};现在,我可以用application.indexedDB.open()打开dbconnection了。现在,我向对象添加了另一个函数:
application.indexedDB.addItemToTable = function(item, table) {
var transaction = application.indexedDB.db.transaction([table], "readwrite");
var store = transaction.objectStore(table);
//Perform the add
var request = store.add(item);
request.onerror = function(e) {
console.log("Error", e.target.error.name);
//some type of error handler
}
request.onsuccess = function(e) {
console.log("Woot! Did it");
}
};我的指令序列扩展如下:
application.indexedDB.open()application.indexedDB.addItemToTable(item, "journal")但这不管用。因为开放指令是异步的,所以当我在addItemToTable-函数中调用它时,application.indexedDB.db是不可用的。Javascript-Developer如何解决这个问题?
我在这里学习本教程:http://code.tutsplus.com/tutorials/working-with-indexeddb--net-34673,现在我在这些例子中遇到了一些问题。
例如,他直接在"onsuccess"-Part (在“读取更多数据”部分)中创建HTML。在我看来,这是不好的编码,因为视图与数据库读取部分没有任何关系。难到不是么?但接下来是我的问题。你怎么能在“一次性成功”-Part中返回一些东西呢?添加回调函数有点复杂。特别是当我想要读一些数据时,用这个结果集可以得到更多的数据。描述我的意思很复杂。我做了个小小提琴-也许它澄清了一些事情..。-- http://jsfiddle.net/kb8nuby6/
谢谢
发布于 2014-09-24 14:10:22
你不需要使用别人的额外程序。在使用indexedDB之前,您需要了解异步javascript (AJAX)。没有办法避免这种情况。您可以在不了解indexedDB的情况下了解AJAX。例如,看看XMLHttpRequest是如何工作的。了解setTimeout和setInterval。也许可以了解一下requestAnimationFrame。如果您知道nodejs的内容,请查看process.nextTick。了解函数是如何一流的。了解使用回调函数的想法。学习延拓传递样式。
对于这个问题,你可能得不到你想要的答案。如果有的话,这是堆栈溢出中有关javascript中异步编程的数千个其他问题的重复。它甚至与indexedDB无关。看看有关异步js的许多其他问题。
也许这会让你开始:
var a;
setTimeout(function() { a = 1; }, 10);
console.log('The value of a is %s', a);弄清楚为什么不起作用。如果你这样做了,你将更接近于找到这个问题的答案。
发布于 2014-09-23 23:05:24
我通常采用的模式是等待所有数据库操作直到连接。它与$.ready在jQuery中的概念是相似的。
您会发现,随着应用程序的老化,您有许多模式版本,并且还需要升级数据。数据库连接本身有很多逻辑。
如果需要在准备就绪之前使用数据库,则可以使用回调队列。以下是谷歌在推荐队列上的分析片段
// Creates an initial ga() function. The queued commands will be executed once analytics.js loads.
i[r] = i[r] || function() {
(i[r].q = i[r].q || []).push(arguments)
},基本上,一旦数据库连接起来,您将执行这些回调。
我强烈建议查看我自己的库,ydn-db。它包含了所有这些概念。
https://stackoverflow.com/questions/26003623
复制相似问题