typescriptoop

How do I wait for the constructor to execute before executing its methods?


I need the file to be read synchronously in the constructor and only then can I use the methods of the class

I am writing a small library for redis. I have such a constructor

constructor(...) {
        this.client = new Redis(...)

        fs.readFile('<the path to Lua scripts>', (err, data)=> {
            if(!err) {
                this.client.call('FUNCTION', 'LOAD', 'REPLACE', data.toString())
            } else {
                ...
            }
        })
    }

which is executed correctly, but since reading the file and writing to the radish occur asynchronously, it turns out that I can use the methods of this class before the script is in the radish. And the methods just use the same scripts that are loaded in the constructor. I understand that I can upload scripts to a separate method, but still I want the library user to be able to simply create an instance of the class and work with it immediately, without calling out any methods for uploading scripts to radish.

I would be grateful if someone would share a good solution to this problem!


Solution

  • By creating a static async function, that creates the object and then call the private loader, you get a function that, if you await for it, creates and initializes the object before you do anything else.

    class Example {
      static async create(...args) {
        const instance = new this(...args);
        await instance.#loader();
        return instance;
      }
      async #loader() {
        console.log('loading');
        await new Promise((resolve) => setTimeout(resolve, 1000));
        console.log('loaded');
      }
    
      constructor() {}
    }
    
    console.log(await Example.create());
    console.log('ready');