0

I couldn't find any proper solution for this problem, so I'm asking here. I'm working with indexedDB that is not really relevant, just mention it for better understanding. I have a function telling me if an object is already stored in the indexedDB. If so, the version of the object will be returned, else value -1.

The Javascript function looks like this:

function dbGameVersion (key) {
    var transaction = db.transaction(["file"]);
    var objectStore = transaction.objectStore("file");
    var request = objectStore.get(key);
    var version = 0;

    // Triggered by objectStore.get(key);
    request.onsuccess = function(event) {
        if(request.result) {
            // Return stored game version
            version = request.result.file.game[0].version;
        } else {
            // Game not yet in DB
            version = -1;
        }
    };

    return version;
}

The code in general works fine, so the question is: How can I pass the version value from the onsuccess event back to the dbGameVersion function, so the function dbGameVersion returns the version value to where it was called from?

I am aware that "var version = 0; ... return version;" is not working since the onsuccess event is acting independent and async. I've just added that for better understanding what I want.

So what is the official/proper solution

Jonny
  • 816
  • 10
  • 24
  • Can you tell me, where exactly are you calling that event handler function, i.e. where are you receiving the return value? Well, nowhere, there's no official solution, you simply can't return from an event handler. – Teemu Aug 13 '18 at 12:17
  • @Teemu Sorry, yeah, indexedDB is a bit special. The onsuccess event is triggered by "var request = objectStore.get(key);". Sample with comments enhanced. – Jonny Aug 13 '18 at 12:21

1 Answers1

1

You cannot return the version value but a promise of it:

function dbGameVersion (key) {
    var transaction = db.transaction(["file"]);
    var objectStore = transaction.objectStore("file");
    var version = 0;

    return new Promise(function(resolve) {
        var request = objectStore.get(key);
        request.onsuccess = function(event) {
            if(request.result) {
               // Return stored game version
               version = request.result.file.game[0].version;
            } else {
            // Game not yet in DB
               version = -1;
            }
            resolve(version);
        };        
    });
}

// And you can then use this function like below:

dbGameVersion(key).then(function(version) {
    // You get the version value here:
    console.log(version);
});
Faly
  • 13,291
  • 2
  • 19
  • 37