Jam*_*ker 3 javascript arrays jquery asynchronous indexeddb
我在 IndexedDB 表中有一些数据,其中非常简单地包含这些数据:
var Customers = [
{ ssn: "123-45-6666", name: "Andrew", age: 22, email: "andrew@hotmail.com" },
{ ssn: "555-66-7777", name: "Gail", age: 25, email: "gail@email.me" }
];
Run Code Online (Sandbox Code Playgroud)
然后我有这个函数从 IndexedDB 取回数据:
function RetrieveTableRows(Table) {
var returnData = [];
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
return;
}
returnData.push(result.value);
result.continue();
};
return returnData;
}
Run Code Online (Sandbox Code Playgroud)
我意识到它不起作用,因为 onsuccess 函数是异步的,但是我无法解决解决方案。
简单地说,我希望能够写:
var myCustomers = RetrieveTableRows('customers');
Run Code Online (Sandbox Code Playgroud)
然后能够使用变量 myCustomers - 这可能吗?
我试过使用JQuery.deferred();方法,但这似乎不起作用,我知道我可能会做这样的事情:
transaction.oncomplete = function() {
ReturnTableRows(returnData);
};
}
function ReturnTableRows(data) {
//do something with the array of data
}
Run Code Online (Sandbox Code Playgroud)
但我不知道如何将它传递回myCustomers变量。
使用延迟对象,你应该能够做这样的事情
function RetrieveTableRows(Table) {
var returnData = [];
//setup deferred object
var defer = $.Deferred();
var db = window.indexedDB.db;
var trans = db.transaction([Table], "readwrite");
var store = trans.objectStore(Table);
var keyRange = IDBKeyRange.lowerBound(0);
var cursorRequest = store.openCursor(keyRange);
cursorRequest.onerror = window.indexedDB.onerror;
cursorRequest.onsuccess = function(e) {
var result = e.target.result;
if(!!result == false) {
//when done resolve the promise, you could also do more
//checking and reject the data so you can handle
//errors
defer.resolve(returnData);
//Make sure we exit the function once we run out of data!
return
}
returnData.push(result.value);
result.continue();
};
//return the promise
return defer.promise();
}
//########### then to use this ###########
//this is now a promise
var myCustomersPromise = RetrieveTableRows('customers');
var myCustomers;
//action todo when promise is resolved/rejected
$.when(myCustomersPromise ).done(function(data){
//do something with the data/assign it to you var here
myCustomers= data;
}).fail(function(data){
});
Run Code Online (Sandbox Code Playgroud)
虽然我之前没有实际使用过 indexedDB,所以可能误解了查询如何知道它已完成(我假设再次result.continue()调用,onSuccess并且在遍历所有数据时结果为 false)但这是我在异步执行任何操作时使用的设置在我的应用程序中
| 归档时间: |
|
| 查看次数: |
3275 次 |
| 最近记录: |