I have a very basic indexedDB with one key. I would like to retrieve this value to perform an operation. Unfortunately, the function that is supposed to do it returns undefined
before indexedDB could return the value.
Here are the functions:
const getValue = async () => { const res = await IndexedDB.get(1) return console.log("res", res) // displayed before "res" has finished }; export default class IndexedDB { static createDB() { const request = indexedDB.open("myApp", 1); request.onupgradeneeded = (e) => { const db = e.target.result; return db.createObjectStore("myData", { autoIncrement: true }); }; } static addData(data) { const db = indexedDB.open("myApp", 1); db.onsuccess = (e) => { const request = e.target.result.transaction(["myData"], "readwrite").objectStore("myData").add(data); request.onsuccess = (res) => res.target.result; request.onerror = (err) => err }; } static get(key) { const db = indexedDB.open("myApp", key); db.onsuccess = (e) => { const request = e.target.result.transaction(["myData"]).objectStore("myData").get(key); request.onsuccess = (res) => res.target.result; request.onerror = (err) => err }; } }
How to fix this?
Your IndexedDb.get
function is not async, but you are awaiting it for some reason?
Change it to:
static get(key) {
return new Promise((resolve, reject) => {
const db = indexedDB.open("myApp", key);
db.onsuccess = (e) => {
const request = e.target.result
.transaction(["myData"])
.objectStore("myData")
.get(key);
request.onsuccess = (res) => resolve(res.target.result);
request.onerror = (err) => reject(err);
};
});
}
The IndexedDb.get
has some async operations indexedDB.open("myApp", key)
. To handle this kind of sync function you need to either use a promise or you can use a callback function.
Using Promise
static get(key) {
let resolve, reject;
const promise = new Promise((re, rj) => { resolve = re; reject = rj; }),
db = indexedDB.open("myApp", key);
db.onsuccess = (e) => {
const request = e.target.result
.transaction(["myData"])
.objectStore("myData")
.get(key);
request.onsuccess = (res) => resolve(res.target.result);
request.onerror = (err) => reject(err);
};
return promise;
}
Using Callbacks
static get(key, successCB, errorCB) {
db.onsuccess = (e) => {
const request = e.target.result
.transaction(["myData"])
.objectStore("myData")
.get(key);
request.onsuccess = successCB;
request.onerror = errorCB;
};
}
// get(key, (res) => {}, (err) => {})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.