0

I tried many ways to get values from my asynchronous function. But, the only thing I could do is get this value using another asynchronous function. Is it not possible to store it into a global variable which will be used then to send datas with AJAX?

Here is my code :

    geocoder.geocode({'latLng': latlng}, function(results, status) {
       if (status == google.maps.GeocoderStatus.OK) 
       {
          if (results[0]) 
          {
              var elt = results[0].address_components;
              for(i in elt)
              {
                 if(elt[i].types[0] == 'postal_code')
                 {        
                     getResults(elt[i].long_name.substring(0, 2));
                 }
              }
          }
       }
       else
       {
           alert("Le geocodage n\'a pu etre effectue pour la raison suivante: " + status);
       }
  });

    getPostalCode(source, function(dpt){
         alert(dpt);
    })

This is not duplication, I read How do I return the response from an asynchronous call? but, I couldn't find what I needed.

Kuartz
  • 302
  • 2
  • 5
  • 23
  • I really do think this is a duplicate of the other question - could you try and phrase your question differently? The short answer is: you can't; use the value in place (i.e. in the function where it is in scope). – gypsydave5 Nov 23 '18 at 13:41
  • You can store a promise in a global variable (or better yet; return it) and make geocode a [promise returning function](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises). A function needs to return something immediately but the result of a web request is available later. It's like you asking me for tomorrows lottery numbers and me requiring your phone number so I can `call you` when the numbers are drawn. – HMR Nov 23 '18 at 13:42

1 Answers1

0

Can you please explain which value you are trying to store in a global? It is not clear from your description. Some additional context would help answer your question. I assume that you are following the Geocoding Service docs?

Have you tried passing the value you are trying to retrieve in a callback?

  • 'elt[i].long_name.substring(0, 2)' is the value that I need to store into a variable. But anyway I think I do like I mentionned. – Kuartz Nov 23 '18 at 14:03