Click here to Skip to main content
15,030,567 members
Please Sign up or sign in to vote.
1.80/5 (2 votes)
I am Using Async Await but still not able to store value or use value outside the function

What I have tried:

<pre><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

let addr = [];
var lati;
var long;
var KEY;
var LAT;
var LNG;
let data;
var urlval;
let a;



function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else { 
    console.log("Geolocation is not supported by this browser.");
  }
}



function showPosition(position) {
  lati = position.coords.latitude;
  long = position.coords.longitude;
   KEY = "APIKEY";
   LAT = lati;
   LNG = long;
   let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${LAT},${LNG}&key=${KEY}`;
   data = fetchData(url);
   console.log(data); // This Works
   return url;
}





  

 

  async function fetchData(url){
        let response = await fetch(url);
        let data = await response.json();
        //console.log(data);
        return data;
      }

 





window.onload = getLocation();

//console.log(data); // Doesnt Work


    </script>
</body>
</html>
Posted
Updated 13-Apr-21 7:48am

1 solution

You haven't understood how async and await work.

The result of an async function is a Promise, which will be resolved at some later time with the actual return value. Inside another async function, you can await that Promise to get the return value:
JavaScript
async function showPosition(position){
    ...
    data = await fetchData(url);
    console.log(data);
}
Outside of an async function, you have to sign up to the Promise object's success callback:
JavaScript
function showPosition(position){
    ...
    fetchData(url).then(function(result){
        data = result;
        console.log(result);
    });
}
Both versions are equivalent. In both cases, you cannot access the return value until the promise has been resolved.

You also don't want the parentheses on the window.onload line - that calls the function and assigns the result to the event, rather than adding the function as a handler for the event.

Change your code to:
JavaScript
async function fetchData(url){
    let response = await fetch(url);
    let data = await response.json();
    return data;
}

async function showLocation(position){
    const KEY = "APIKEY";
    let lat = position.coords.latitude;
    let long = position.coords.longitude;
    let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${KEY}`;
    let data = await fetchData(url);
    console.log(data);
    ... USE THE DATA HERE ...
}

function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else { 
        console.log("Geolocation is not supported by this browser.");
    }
}

window.addEventListener("load", getLocation);

async function - JavaScript | MDN[^]
Using Promises - JavaScript | MDN[^]
EventTarget.addEventListener() - Web APIs | MDN[^]
   
Comments
Nawaz Pasha 2021 13-Apr-21 13:48pm
   
Thank you Very Much this info was great, but still, I want to use data variables outside, globally in the program how can I do that.I tried its still showing undefined, please help me out it would be great
Richard Deeming 14-Apr-21 4:26am
   
You can't use the variable returned from the fetch request until the fetch request has returned.

You need to re-think the structure of your code; either make the whole thing an async function, or move the code that's using the variable into a continuation function for the Promise.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900