【问题标题】:Calling other functions of a class inside a Promise in Node在 Node 的 Promise 中调用类的其他函数
【发布时间】:2021-04-23 12:03:25
【问题描述】:

所以,我在一个类中有两个方法。两者都返回一个承诺。第二个函数从它返回的 Promise 内部调用第一个函数。

module.exports = {
 funcA: () => {
  return new Promise((resolve, reject) => {
       something ? resolve(something): reject('nope');
  });
 }

 funcB: () => {
    return new Promise(async(resolve, reject) => {
            try {
                const something = await this.funcA();
            } catch(err) {
                reject('error');
    }
 }
}

当我尝试从另一个类调用 funcB() 时,如下所示:

let something = await someService.funcB();

我得到:

TypeError: this.funcA() is not a function

您能否解释一下为什么会发生这种情况以及如何解决这个问题?

【问题讨论】:

  • 停止使用new Promise,你的所有问题都会神奇地消失;)

标签: javascript node.js promise this es6-promise


【解决方案1】:

使其工作的一种方法是在module.exports 块之外创建函数以获取每个函数的引用。那么this关键字可以省略

const funcA = () => {
  return new Promise((resolve, reject) => {
    // code here
  });
};

const funcB = () => {
  return new Promise(async(resolve, reject) => {
    try {
        const something = await funcA();
        resolve(something);
    } catch(err) {
        reject('error');
    }
  })
};

module.exports = {
  funcA,
  funcB
}

【讨论】:

    【解决方案2】:

    我认为这是你需要做的

    module.exports = {
     funcA: function() {
      return new Promise((resolve, reject) => {
           something ? resolve(something): reject('nope');
      });
     }
    
     funcB: function() {
        return new Promise(async(resolve, reject) => {
                try {
                    const something = await this.funcA();
                } catch(err) {
                    reject('error');
        }
     }
    }
    

    我发现在对象中使用箭头函数就像你所做的那样打破了this,但你可以通过这种方式修复它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-22
      • 2020-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多