sofa_maniac
sofa_maniac

Reputation: 1647

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?

Upvotes: 1

Views: 470

Answers (2)

elpmid
elpmid

Reputation: 932

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
}

Upvotes: 4

TKoL
TKoL

Reputation: 13892

I think this is what you need to do

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

I've found using arrow functions inside objects as you've done breaks this, but you can fix it this way.

Upvotes: 3

Related Questions