无法控制台日志数组数据

时间:2021-03-28 11:18:42

标签: javascript promise

所以基本上这是获取用户位置的代码,从Promise获取数据后我无法在外面使用它,我尝试使用推送数组对象但无法使用其值。 Previously I got help i tried the same thing yet the same problem 我是 js 新手,任何人都可以帮忙

let addr = [];
var lati;
var long;

const init = async() => {
  const todo = await geo(1);
  console.log(todo);
};

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;
  init();
}

const geo = async(id) =>
  new Promise((resolve, reject) => {
    const KEY = "APIKEY";
    const LAT = lati;
    const LNG = long;
    let url = `https://maps.googleapis.com/maps/api/geocode/json?latlng=${LAT},${LNG}&key=${KEY}`;

    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        resolve(data);
        console.log(data);
        addr.push(data.results[0].formatted_address);
      })

      .catch((err) => console.warn(err.message));
  });

window.onload = getLocation();
console.log(addr[0]);

0 个答案:

没有答案