如何在 Javascript 中按承诺启动 class 函数?
How to launch a class function on promise in Javascript?
我有以下 class:
let graphFactory = new GraphFactory();
function GraphFactory(){
let value = 'something';
this.release = function() {
return value;
}
}
现在,当我尝试以这种方式从程序中的另一个地方调用此函数时:
let newvalue = graphFactory.release();
无法识别graphFactory
,因为加载此功能需要一些时间。
我想通过在 graphFactory
完全加载并激活时发出一个承诺来解决这个问题,但是当我试图将一个函数添加到 GraphFactory
函数中时,比如
function GraphFactory(){
let value = 'something';
this.release = function() {
graphFactoryPromise(value);
}
}
然后
function graphFactoryPromise() {
return new Promise(function(resolve,reject) {
resolve('loaded');
});
}
并将其称为
graphFactoryPromise().then(function(result) {
let newvalue = result;
});
还是不行(graphFactory
无法识别)。
对此有什么好的解决方案?
更新
我想要的是仅在定义和加载 graphFactory
之后才能调用函数 graphFactory.release()
。
尝试release()
作为承诺:
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;}
我有以下 class:
let graphFactory = new GraphFactory();
function GraphFactory(){
let value = 'something';
this.release = function() {
return value;
}
}
现在,当我尝试以这种方式从程序中的另一个地方调用此函数时:
let newvalue = graphFactory.release();
无法识别graphFactory
,因为加载此功能需要一些时间。
我想通过在 graphFactory
完全加载并激活时发出一个承诺来解决这个问题,但是当我试图将一个函数添加到 GraphFactory
函数中时,比如
function GraphFactory(){
let value = 'something';
this.release = function() {
graphFactoryPromise(value);
}
}
然后
function graphFactoryPromise() {
return new Promise(function(resolve,reject) {
resolve('loaded');
});
}
并将其称为
graphFactoryPromise().then(function(result) {
let newvalue = result;
});
还是不行(graphFactory
无法识别)。
对此有什么好的解决方案?
更新
我想要的是仅在定义和加载 graphFactory
之后才能调用函数 graphFactory.release()
。
尝试release()
作为承诺:
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;}