menu

Questions & Answers

IndexedDB wait for event

I'm having a problem with IndexedDB when trying to retrieve data from an object store.

 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;
    }
}

Basically I have a function that I want to return the retrieved value so I can use it to set and input element, Problem is the function doesn't wait for the events and just returns nothing because it hasn't got any data yet. Function looks like this How can I tell it to wait for "onsuccess" to finish before returning?

Any help is greatly appreciated.

Comments:
2023-01-24 23:10:08
Is the console.log logging the correct data?
2023-01-24 23:10:08
Yes sorry should have said. the console.log displays the correct data so I can see it is actually retrieving the data correctly.
2023-01-24 23:10:08
Ok - do you use ES6 features?
2023-01-24 23:10:08
I don't think I have any ES6 features currently in the code anywhere
Answers(1) :

Possible solution with a 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);
            }
        }
    });
}

Then implement it like this:

const result = await getLayoutData();
// Do whatever you want with the data

Generally you'd need a (promise polyfill) to make it work with browsers that don't support promises yet (IE for example). Since IE doens't support indexedDB anyway, you don't have to use it for this case.

Comments:
2023-01-24 23:10:08
a life saver answer! thanx