Search code examples
javascriptnode.jspromisethises6-promise

Calling other functions of a class inside a Promise in Node


So, I have two methods in a class. Both returns a promise. The second function calls the first function from inside of the promise it returns.

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

When I am trying to call funcB() from another class, like this:

let something = await someService.funcB();

I am getting:

TypeError: this.funcA() is not a function

Can you shed some light on why this is happening and how to solve this problem?


Solution

  • one way to make it work is to create the function outside of the module.exports block to get a reference of each function. Then this keyword can be omitted

    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
    }