如何在Javascript中按承诺启动类函数? [英] How to launch a class function on promise in Javascript?

查看:81
本文介绍了如何在Javascript中按承诺启动类函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程:

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();

它不识别 graphFactory ,因为它需要

我想通过在 graphFactory 完全加载时发出一个承诺来解决此问题。并被激活,但是当我尝试向 GraphFactory 函数中添加

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

然后

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

并称其为

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

它仍然不起作用( graphFactory 无法识别)。

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

有什么好的解决方案?

UPDATE
我想要的是仅在定义并加载 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;}

这篇关于如何在Javascript中按承诺启动类函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆