Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 597
Will Robson Avatar asked Jan 28 '23 13:01

Will Robson


1 Answers

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.

like image 85
sandrooco Avatar answered Jan 31 '23 07:01

sandrooco