0
votes

so I have this nightmare code that worked perfectly fine and I put it into a class. However it started throwing promise errors :-( (without the fun() function it works fine.

class test {
  constructor() {
    this.init(() => {
      this.start()
    })
  }

  init() {
    this.nightmare = new Nightmare({
      show: true,
      typeInterval: 20,
      openDevTools: {
        detach: true
      }
    });
  }

  async start() {

    await this.nightmare
      .useragent(userAgent)
      .goto("https://www.yahoo.com")

    fun();

    async function fun() {
      await this.nightmare.goto('https://google.com')
    }
  }
}

new test().start();

The error is:

(node:1101) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: Cannot read property 'nightmare' of undefined

(node:1101) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1
Wrap your await this.nightmare.goto('https://google.com') in a try catchdzm
have you tried await fun();? and what happens if you move the call after the function initialization?Get Off My Lawn

1 Answers

1
votes

This doesn't really have anything to do with promises or await. You are getting an error because this does not refer to your object inside fun(). When you create a function and call it like you are with fun() you loose the this reference to your object. Consider:

class test {
    constructor() {
        this.init()
    }
    
    init() {
        this.prop = "a property"
    }
    start() {
        console.log("this outside of fun: ", this)
        fun()
        function fun(){
            console.log("this in fun:", this)
        }
    }
}     
new test().start()

You will see that this is undefined in fun().

Consider making fun() a real method and call it with this.fun() Alternatively you can manually bind this with something like:

 fun.call(this)