IndexedDB 等待事件
IndexedDB wait for event
我在尝试从对象存储中检索数据时遇到 IndexedDB 问题。
function GetLayoutData(key) {
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var open = indexedDB.open("DB", 1);
open.onsuccess = function () {
db = open.result;
tx = db.transaction("Store", "readwrite");
var store = tx.objectStore("Store");
store.get(key).onsuccess = function (event) {
console.log(event.target.result);
return event.target.result;
}
}
基本上我有一个函数,我想 return 检索到的值,所以我可以用它来设置和输入元素,问题是函数不等待事件,只是 return 没什么,因为它还没有任何数据。功能看起来像这样
我怎样才能告诉它在 returning 之前等待 "onsuccess" 完成?
任何帮助都非常有用。
可能的解决方案 Promise
;
function getLayoutData (key) {
return new Promise (function(resolve) {
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var open = indexedDB.open ("DB", 1);
open.onsuccess = function () {
db = open.result;
tx = db.transaction("Store", "readwrite");
var store = tx.objectStore("Store");
store.get(key).onsuccess = function (event) {
return resolve(event.target.result);
}
}
});
}
然后这样实现:
getLayoutData().then(function(result) {
// Do whatever you want with the data
});
通常,您需要一个 (promise polyfill) 才能使其与尚不支持 promises 的浏览器(例如 IE)一起使用。由于 IE 无论如何都不支持 indexedDB,因此您不必在这种情况下使用它。
我在尝试从对象存储中检索数据时遇到 IndexedDB 问题。
function GetLayoutData(key) {
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var open = indexedDB.open("DB", 1);
open.onsuccess = function () {
db = open.result;
tx = db.transaction("Store", "readwrite");
var store = tx.objectStore("Store");
store.get(key).onsuccess = function (event) {
console.log(event.target.result);
return event.target.result;
}
}
基本上我有一个函数,我想 return 检索到的值,所以我可以用它来设置和输入元素,问题是函数不等待事件,只是 return 没什么,因为它还没有任何数据。功能看起来像这样 我怎样才能告诉它在 returning 之前等待 "onsuccess" 完成?
任何帮助都非常有用。
可能的解决方案 Promise
;
function getLayoutData (key) {
return new Promise (function(resolve) {
indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB || window.shimIndexedDB;
var open = indexedDB.open ("DB", 1);
open.onsuccess = function () {
db = open.result;
tx = db.transaction("Store", "readwrite");
var store = tx.objectStore("Store");
store.get(key).onsuccess = function (event) {
return resolve(event.target.result);
}
}
});
}
然后这样实现:
getLayoutData().then(function(result) {
// Do whatever you want with the data
});
通常,您需要一个 (promise polyfill) 才能使其与尚不支持 promises 的浏览器(例如 IE)一起使用。由于 IE 无论如何都不支持 indexedDB,因此您不必在这种情况下使用它。