我使用IndexedDB在客户端存储数据,以便在应用中切换标签时保存数据,使用.get()方法时无法获取onsuccess事件的返回值,请指教。
下面是代码
sample.js
function getFromIndexedDbSession(key)
{
let db;
const openRequest = indexedDB.open('tool', 1);
openRequest.onupgradeneeded = function (e) {
db = e.target.result;
const storeOS = db.createObjectStore('tool');
};
openRequest.onsuccess = function (e) {
db = e.target.result;
getRequest = db.transaction('tool').objectStore('tool').get(key);
getRequest.onsuccess = (e)=> {
const student = e.target.result;
console.log(student)
return student; //**This is not working, How can I return student value??**
}
getRequest.onerror = (err)=> {
console.error(`Error to get student information: ${err}`)
}
};
openRequest.onerror = function (e) {
console.log('onerror! doesnt work');
};
}
data = getFromIndexedDbSession("lan"); //here result of data is **undefined**, i want return value here
如何将onsuccess事件的返回值导入数据变量?
谢啦
1条答案
按热度按时间eoigrqb61#
问题是
getFromIndexedDbSession
是异步的,get
操作通过事件处理程序`返回一个值。您可以尝试返回结果以等待它:
然后,你可以使用Promise来获取student的值: