无法达到价值...... ReactJS

时间:2018-03-23 02:42:24

标签: javascript reactjs ecmascript-6

我目前无法访问函数中的值。

这是我的代码:

distanceBool = (event) => {
    console.dir(event);

    let address = ["Toronto, ON, CA"];

    let destination = ["Vancouver"];

    let location = this;

    let service = new window.google.maps.DistanceMatrixService();
    new Promise((resolve)=>{
      resolve(
        service.getDistanceMatrix({
        origins: ["Waterloo ON"],
        destinations: destination,
        travelMode: 'DRIVING',
        avoidHighways: false,
        avoidTolls: false
      }, function(response, status){
       if (status == 'OK') {
         var origins = response.originAddresses;
         var destinations = response.destinationAddresses;

         for (var i = 0; i < origins.length; i++) {
           var results = response.rows[i].elements;
           for (var j = 0; j < results.length; j++) {
             var element = results[j];
             var distance = element.distance.text;
             var duration = element.duration.text;
             var from = origins[i];
             var to = destinations[j];

             location.distFinal = distance;

             location.setState({
               dist: distance
             })

           }
         }

       }
     })

      )
    }).then((res)=>{
      // console.log(res)
      // console.dir(location);
      console.dir(location);
      console.dir(location.distFinal);
      // console.log("hello")
    })


}

我正在尝试访问距离,所以我做了console.dir(location.distFinal),但它给了我一个未定义的值。 但是,当我做console.dir(location)时,它给了我带有distFinal的对象作为值....

这就是我的意思:

enter image description here

第132行是console.dir(位置),第133行是console.dir(location.distFinal)

请!我只是希望能够提取距离!

1 个答案:

答案 0 :(得分:1)

您的顶级承诺立即解析 - 您可能只想在内部异步代码完成后解析。

new Promise((resolve)=>{
  service.getDistanceMatrix({
    origins: ["Waterloo ON"],
    destinations: destination,
    travelMode: 'DRIVING',
    avoidHighways: false,
    avoidTolls: false
  }, function(response, status){
    if (status !== 'OK') return;
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      for (var j = 0; j < results.length; j++) {
        var element = results[j];
        var distance = element.distance.text;
        var duration = element.duration.text;
        var from = origins[i];
        var to = destinations[j];

        location.distFinal = distance;
        location.setState({
          dist: distance
        })
      }
    }
    // all the looping is done:
    resolve();
  })
}).then((res)=>{
  // console.log(res)
  // console.dir(location);
  console.dir(location);
  console.dir(location.distFinal);
  // console.log("hello")
})