I have the following class:

let graphFactory = new GraphFactory();

function GraphFactory(){
    let value = 'something';
    this.release = function() {
        return value;
    }
} 

Now, when I try to call this function from another place in my program in this way:

let newvalue = graphFactory.release();

It does not recognize graphFactory because it takes some time to load this function.

I would like to resolve this by issuing a promise when graphFactory is fully loaded and activated, but when I tried to add a function into GraphFactory function like

function GraphFactory(){
    let value = 'something';
    this.release = function() {
        graphFactoryPromise(value);
    }
} 

and then

function graphFactoryPromise() {
     return new Promise(function(resolve,reject) {
            resolve('loaded');
     });
}

and calling it as

graphFactoryPromise().then(function(result) {
    let newvalue = result;
});

It still doesn't work (graphFactory is not recognized).

What would be a good solution to this?

UPDATE What I want is to be able to call the function graphFactory.release() only after graphFactory is defined and loaded.

1 Answers

1
Dennis Vash On Best Solutions

Try release() as a promise:

const graphFactory = new GraphFactory();

function GraphFactory() {
  this.value = 'Something';

  const graphFactoryPromise = () =>
    new Promise(resolve => setTimeout(() => resolve('new-Something'), 1000));

  // Release is a promise
  this.release = async () => {
    this.value = await graphFactoryPromise(); // New Result
    return this.value;
  };
}

console.log(graphFactory.value);
graphFactory.release().then(console.log);
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}