0

How can I use this inside a callback? Using callback, I got undefined on this.callback() (this is undefined):

    constructor(collection, journey, callback, environment=null) {
        this.collection = collection;
        this.journey = journey;
        
        this.callback = callback;
        console.log(this.callback)
        this.environment = environment;       
    }

    run() {

        newman.run({
            collection: this.collection,
            environment: this.environment,
            insecure: true
        }, this.internalCallback).on('console', function (err, args) { 
            console.log(args.messages.join(' '));
        })

    }

    internalCallback(error, summary) {
        if(error || summary.error) throw (error || summary.error)
        console.log(this)
        this.callback(this.journey, summary) // here throws an error because this is undefined
    }
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
placplacboom
  • 614
  • 8
  • 16

2 Answers2

0

I assume that newman.run creates a new "this" context in your code. Have you tried binding the function: this.internalCallback.bind(this) to this of your class when passing it to newman.run?

Try this code:

run() {

    newman.run({
        collection: this.collection,
        environment: this.environment,
        insecure: true
    }, this.internalCallback.bind(this)).on('console', function (err, args) { 
        console.log(args.messages.join(' '));
    })

}
twboc
  • 1,452
  • 13
  • 17
0

Can you try something like this:

that = this;
constructor(){
}
internalCallback(error, summary) {
  if(error || summary.error) throw (error || summary.error)
  console.log(this)
  that.callback(that.journey, summary) // here throws an error because this is undefined
}