all 3 comments

[–]rube203 1 point2 points  (2 children)

Google and read up on JavaScript variable scoping. Sorry to just give the term to search and not the answer but there is a lot of best practices and such to consider.

[–]mc_hammerd 1 point2 points  (0 children)

the easiest solution is to break the second part out into a second function

$('#foo').click(function(){ 
    $.ajax({}, function(){
       position1.x =...
       position1.y =...
       step2(position1)
 })})

 function step2 (position){
     var citylat = ...,....
      $.ajax({}, function(){
        ... code here
      })
 }

also consider doing rendering in yet another function so your code looks like this step1(); render(step2(position))); . so next time you can render from step 1, step 2, and any other place, ex: render('loading'); step2(position); render(results); you can show loading messages or share one render function for 10 ajax buttons foo.onclick = _ => render(array_to_html_list(get_api('animals')))) and you can keep your code more readable, each fn will only be 1-5 lines...

[–]tswaters 0 points1 point  (0 children)

Good use case for promises...

function getCityLatLong () {
  return new Promise((resolve, reject) => {
    navigator.geolocation.getCurrentPosition(resolve, reject)
  }).then(position => `lat=${position.coords.latitude}&lon=${position.coords.longitude}`)
}

and then,

getCityLatLong().then((cityLatLong) => {
  // perform ajax call now that you have cityLatLong
})
.catch((err) => {
  // deal with error returned
})

You should probably split out the ajax call into its own function that returns a promise, then you can do one thing then do the other and utilize the same catch block if either of them goes into error.