1

I am trying to access MethodA within an async function inside MethodB, which is not accessible. But if i am trying outside async function it is working as expected. Below is the example.

Options tried and not working:

  1. Used this.methodA()
class A{
constructor(){
}

async methodA(){
//Do something here
}

async methodB(){
await methodA(); //methodA is accessible in this line
await browser.getCurrentUrl().then(async function(){
await methodA(); //methodA is NOT accessible in this line
});
}
}

module.exports = new A(); //Using this to make the methods available in other places
mkcodex
  • 11
  • 3
  • Just like for non-async methods, you need to use `this.methodB()` – Bergi Feb 15 '22 at 20:03
  • yes i tried but it was not working either. – mkcodex Feb 15 '22 at 20:05
  • As for calling `this.methodA()` from the `.then()` callback, you need to use an arrow function there as `this` won't refer to the class instance in the `function`. However you shouldn't be using `.then()` at all - just `const url = await browser.getCurrentUrl();` and then write `this.methodA()` in the next line like normal. – Bergi Feb 15 '22 at 20:07
  • If that still doesn't work, please show us how you are calling `methodB`. – Bergi Feb 15 '22 at 20:07
  • Btw, why are you exporting a `new A` instance instead of the class? If you want a singleton object, you shouldn't use `class` syntax but simply an object literal. Instead of trouble with `this`, you can then also refer to the object by its constant name. – Bergi Feb 15 '22 at 20:08
  • Wonderful. Worked. I tried removing .then() and keep it await. (My bad - careless) - This worked. And also changing to arrow function worked. Both got me resolved. – mkcodex Feb 15 '22 at 20:16
  • @Bergi - Could you please direct me how to make use of what you are explaining in this comment --> __"If you want a singleton object, you shouldn't use class syntax but simply an object literal."__ – mkcodex Feb 15 '22 at 20:24
  • Just `module.exports.functionA = async function() { … }; module.exports.functionB = async function() { … };`. Or `module.exports = { async methodA() {…}, async methodB() { … } };`. – Bergi Feb 15 '22 at 20:31
  • Thanks!! Got it! – mkcodex Feb 15 '22 at 20:35

0 Answers0