Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
140 views
Welcome To Ask or Share your Answers For Others

1 Answer

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;}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...