我有这个功能:
this.get = function() {
var something = 0;
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange;
if (!window.indexedDB) {
return;
}
var openRequest = window.indexedDB.open("abc", 1);
openRequest.onupgradeneeded = function (e) {
var thisDB = e.target.result;
if (!thisDB.objectStoreNames.contains("xyz")) {
thisDB.createObjectStore("xyz");
}
}
openRequest.onsuccess = function (e) {
var transaction = e.target.result.transaction(["xyz"], "readwrite");
var store = transaction.objectStore("xyz");
var request = store.openCursor(1);
request.onerror = function (e) {
}
request.onsuccess = function (e) {
something = e.target.result.value.size;
console.log(1);
}
}
openRequest.onerror = function (e) {
}
console.log(2);
return something;
};
正如您所看到的,我希望首先使用'e.target.result.value.size'分配'something',然后返回。
但是,indexeddb是异步的,因此它将返回0而不是'e.target.result.value.size'(这意味着日志将首先打印出2,然后是1)
所以我的问题是,如何返回'e.target.result.value.size'的值
答案 0 :(得分:2)
正如你所说,indexeddb是异步的,这意味着“get”函数不能同步返回e.target.result.value.size。
通常你在这种情况下做的是提供回调“get”,la:
this.get = function(callback) {
...asynchronous operations...
callback(e.target.result.value.size);
}
或者从“获取”返回承诺:
this.get = function() {
return $.Deferred(function(dfd) {
...asynchronous operations...
dfd.resolve(e.target.result.value.size);
}).promise();
}
这使用jQuery的Deferreds(jQuery的promises实现),但你可以使用任何其他实现,例如Q,when,mpromise等。如果你最终使用promises,你会像这样使用“get”:
this.get().done(function(something) {
// use "something"
});
答案 1 :(得分:0)
如果有人仍在尝试使用香草js,您将执行以下操作:
async function xx(){
return new Promise(function(resolve, reject){
let request = ...;
request.onsuccess = function(){
resolve(request.result);
}
});
}
xx().then(function(result){...});