Grupomo Azcollo
Grupomo Azcollo

Reputation: 1

Put data from a IndexedDB data base in a variable

I'm trying to put the data read from the database in a variable. I have tryed many things, including a callback function, but nothing looks to work when the process is outside of the "opencursor().onsuccess" function scope.

The "Alert 1" show the result correctly, but "Alert 2" and "Alert 3" don't.

I'm calling the 'main()' function from HTML code.

I'm really frustrated, because I have been mining internet searching for the solution without any positive result.

Can anybody help me, please?

Thanks a lot.

var data=[];

function kkeyget(t1, db_name, db_version)
{
    var request = indexedDB.open(db_name, db_version);
    request.onerror=function()
    {
     alert("Error");
    }    
    request.onsuccess=function(event)
    {
    var db=this.result; 
    var trans = db.transaction(t1, "readonly");
    var objectStore = trans.objectStore(t1);
    objectStore.openCursor().onsuccess = function(event) 
    {
        var cursor = event.target.result;
        if (cursor) 
        {
         data.push(cursor.value);

         //Alert 1:
         alert(data[0].id);

         cursor.continue();
        }
        else alert("No more entries!");
    };
    }

    //Alert 2:
    alert(data[0].id);
} 

function main()
{
kkeyget("agenda", "example_db", 1);

//Alert 3:
alert(data[0].id);
}

Upvotes: 0

Views: 388

Answers (2)

Josh
Josh

Reputation: 18690

Instead of trying to return a key, pass in a custom callback function that takes the retrieved key as its argument.

// Your old function slightly modified
function kkeyget(t1, db_name, db_version, callback, fallback) {
 // ... yada yada yada
 objectStore.openCursor().onsuccess = function(event) {
   var cursor = event.target.result;
   if(cursor) {
     callback(cursor.value);
   } else {
     fallback();
   }
 }
}


// Now in your calling code:
kkeyget('a','b',1, function(id) {
  // Do something with the 'id'
  // here in this anonymous function callback
}, function() {
  // Do something here to indicate no match
});

Upvotes: 1

Brin Marx
Brin Marx

Reputation: 153

Correct. Because all indexedDB actions are asynchronous, your code will run:
alert 2 // undefined
alert 3 // undefined
alert 1 // correct

In order to get this closer to a synchronous action, you need to have it call a new function after it's done collecting data. Where your alert("No more entries!") is.

Upvotes: 1

Related Questions