0

Explanation of code

I have a function called placeDecode which takes an HTML input element. Within the function I have a promise which converts input value into a formatted address.

I called placeDecode twice, to check when both called have been resolved I use a Promise.all, checking both each function call. My problem arises when I try to call a function viewResult, I get Cannot read property 'viewresult' of undefined error.


Code

  //call function twice
    var startAddress = this.placeDecode1(this.searches.startSearch);
    var endAddress = this.placeDecode1(this.searches.endSearch);
  
    //promise all
    Promise.all([endAddress,startAddress]).then(function(values) {
      this.viewResult(values);

    }).catch(function(result){
      console.log(result);
    })

    console.log('hit');
  }


  //method convertes input into formatted address
  private placeDecode1(input: HTMLInputElement) {

    var result = new Promise(function(resolve, reject) {
      var location = input.value;

      var geoCode = new google.maps.Geocoder();
      geoCode.geocode({
        address: location
      }, function(result,status){
        if(status == 'OK'){
          console.log(result[0].formatted_address);
          resolve(result[0].formatted_address);
        }
      })
    });

    return result;

  }

Problem

The problem I am having is when i call this.viewResult(values); , I get an

Cannot read property 'viewResult' of undefined Error.

many thanks

Akash Dathan
  • 4,348
  • 2
  • 24
  • 45
Yusof Bandar
  • 169
  • 1
  • 4
  • 9

1 Answers1

10

Change:

function(values) {
  this.viewResult(values);
}

To:

(values) => {
  this.viewResult(values);
}

More

Arrow functions bind this based on outer scope.

basarat
  • 261,912
  • 58
  • 460
  • 511