0

I have the following method that gets items form the object store:

self.getSpecificFromDB = function(a, b, c, callback) {
   self.trans = self.db.transaction(['do'], 'readonly');
   self.store = self.trans.objectStore('do');

    var items = [];

   var cursorRequest = self.store.openCursor();

    cursorRequest.onerror = function (event) {
            console.log("Cursor error");
    };
    cursorRequest.onsuccess = function (event) {
            var cursor = event.target.result;
                if (cursor) {
                    if (cursor.value.test == a) {
                        console.log("found it");
                        items.push(cursor.value);
                    }
                    cursor.continue();
                }

    };
  callback(items);
};

I would like to use the array returned in items in the calling method of my viewmodel:

        self.search = function() {
            console.log("search called");
            var resultarray = self.dbinstance.getSpecificFromDB(self.t(), self.d(), self.g(), function(elem) { console.log(elem);});
            console.log(resultarray);
            if (resultarray != undefined && resultarray.length > 0) {
                self.searchitems.push({
                  general: resultarray[0].test,
                  two: resultarray[0].test2,
                  three: resultarray[0].test3
                });
            } else {
                self.errormessagediv("Nothing was found");
            }
        };

The callback itself works, but the resultarray is always undefined, even when I use something like function (item) { return item; } as a callback. How do I get the results to my viewmodel?

user3629892
  • 2,960
  • 9
  • 33
  • 64

1 Answers1

2

You can't return an array in this manner. You need to learn about how to write asynchronous JavaScript. For example of how to use a callback function, indexedDB openCursor transaction onsuccess returns empty array.

This is a question about writing in JavaScript, not indexedDB.

Community
  • 1
  • 1
Josh
  • 17,834
  • 7
  • 50
  • 68
  • well, all the examples I see only ever use console.log...well, that works fine for me too, but the other thing just doesnt. And from what ive seen in other posts now, it doesnt seem possible. So I'll just better populate the respective html tags directly in the cursorRequest.onsuccess function instead of passing any return values... – user3629892 Oct 27 '14 at 08:30
  • ha, I got it!! This post here did it for me: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call . But still, thanks a lot! You gave a a nudge in the right direction! – user3629892 Oct 27 '14 at 10:32