Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

How to launch a class function on promise in Javascript?

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

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

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...