0

I am trying to access JSON data retrieved from JSON-Server within a function outside the function scope for the past 3 hours with no luck, below is my Code:

http.get(`http://localhost:3000/${depairport}`)
  .then(data => airportNav(data))
  .catch(err => console.log(err));

  var number1 = 1.0;
  var number2 = 2.0;

  var airportNav = function calculateDepNav(depNav){
    number1 = depNav.lat;
    number2 = depNav.lon;
    return number1, number2;
  }

console.log(number1, number2);

How should I access depNav outside of this scope?

  • You don't, in this case, just put the console.log() inside of your airportNav Function – Luca Kiebel Apr 07 '18 at 11:53
  • I know that would work, I'm trying to retrieve the lat and long from two different airports in two different functions, then putting them into a separate function to calculate the distace, is there anyway to do this? – Silas Crosby Apr 07 '18 at 11:55
  • _" is there anyway to do this"_ -> `Promise.all()`, and `return number1, number2;` won't do what you might think it does. – Andreas Apr 07 '18 at 11:57
  • If you have to make multiple http requests, you could use Promise.all on an array of these requests and then work with all the data inside of your distance calculator – Luca Kiebel Apr 07 '18 at 11:57
  • understood, but how can I access depNav.lat and depNav.lon outside of the function? – Silas Crosby Apr 07 '18 at 11:59
  • You can't, not if it's async, like right now, they will be undefined outside of their scope – Luca Kiebel Apr 07 '18 at 12:00
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Patrick Hund Apr 07 '18 at 13:19

1 Answers1

0

Got it, was able to do it with the below, used a for loop for html requests then used an if statement to calculate the distance when the html responses were done.

  for(let i=0; i<urls.length; i++){
  http.get(urls[i])
  .then(data => {
    responses.push(data);
    if(responses.length == 2){
    distance(responses[0].lat, responses[0].lon, responses[1].lat, responses[1].lon);

    function distance(lat1, lon1, lat2, lon2) {
      var p = 0.017453292519943295;    // Math.PI / 180
      var c = Math.cos;
      var a = 0.5 - c((lat2 - lat1) * p)/2 + 
              c(lat1 * p) * c(lat2 * p) * 
              (1 - c((lon2 - lon1) * p))/2;

      console.log(12742 * Math.asin(Math.sqrt(a)));
      return 12742 * Math.asin(Math.sqrt(a)); // 2 * R; R = 6371 km
    }
  }

  })
  .catch(err => console.log(err));
  }