-1

I am trying make a function that returns an array of all the objects in an object store. This is the JavaScript code I currently have:

function readAllSessions() {
    var output = [];
    database.transaction("practiceSessions").objectStore("practiceSessions").openCursor().onsuccess = function (e) {
        var cursor = e.target.result;
        if (cursor) {
            output.push(cursor.value);
            cursor.continue();
        }
    }
    return output;
}

This returns an empty array. I found that the cursor object is null, but I can't see why, since there are 3 objects in the object store.

richard2706
  • 45
  • 1
  • 6
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – mpm Sep 23 '18 at 21:57

1 Answers1

3

you can't return anything from a asynchronous call without a callback or a promise, here is a the function implemented with a callback.

function readAllSessions(callback) {
    var output = [];
    database.transaction("practiceSessions").objectStore("practiceSessions").openCursor().onsuccess = function (e) {
        var cursor = e.target.result;
        if (cursor) {
            output.push(cursor.value);
            cursor.continue();
        }else{
          callback(output)
        }
    }
}


readAllSessions(function(output){
   // use output here.
})

for future reference, please read this question and its answers :

How do I return the response from an asynchronous call?

This process is the very essence of working with Web API in the browser.

mpm
  • 20,148
  • 7
  • 50
  • 55