1

I have a class (LoadClass) which inits when the page loads, and opens an SQLite database in my case and executes a couple of queries. Now I want other components to only execute code when LoadClass has previously finished loading the database, but this must happen anytime. For obvious reasons, I only want to open my databases once. It should work something like this:

class LoadClass {

    // This executes directly on page load
    constructor() {
        this.load_my_database().then(function() {
            // My database finished loading, now my buttons may work.
        })
    }
}

function user_presses_button() {
    LoadClass.ready().then(function() {
        // Only now something
    })
}

How would I go about doing this using Promises?

Rik de Vos
  • 3,467
  • 5
  • 28
  • 34

1 Answers1

1
class LoadClass {

    private _ready_promise; 

    constructor() {}

    // This executes directly on page load
    page_load() {
        this._ready_promise = this.load_my_database();
    }

    load_my_database() {
        return new Promise(function(resolve) {
            // Do something...
            // Now my database finished loading, everything else may work.
            return resolve();
        })
    }

    ready() {
        return this._ready_promise;
    }
}

function user_presses_button() {
    LoadClass.ready().then(function() {
        // Only now something
    })
}
Rik de Vos
  • 3,467
  • 5
  • 28
  • 34