无法控制台日志数组数据(从承诺推送)

时间:2021-03-26 18:36:45

标签: javascript promise

所以基本上这是获取用户位置的代码,从Promise获取数据后我不能在外面使用它,我尝试使用推送数组对象但不能使用它的值。

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

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

function revgeo(){
  const KEY = "api";
  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 => {
          addr.push(data.results[0].formatted_address);
          console.log(data);
        })
        .catch(err => console.warn(err.message));
}


window.onload = getLocation();

console.log(addr); // this works
console.log(addr[0]); // this doesn't work

1 个答案:

答案 0 :(得分:2)

问题在于,当您调用 google API(即您的 fetch 操作)时,它需要几毫秒才能完成。您下面的代码(在您的 fetch 回调之外)在 fetch 调用完成之前执行。这是正在发生的事情的示例。

let todo = null;
fetch('https://jsonplaceholder.typicode.com/todos/1')
  .then(response => response.json())
  .then(json => {
    todo = json;
    console.log('First Log', todo);
  })
  
  console.log('Second Log', todo);

注意 Second LogFirst Log 之前是如何发生的。

要解决此问题,您可以简单地移动您的逻辑,使其发生在您的回调中,因此在 fetch 调用完成之前不会执行。另一种选择是使用 async/await

const getTodo = async (id) => fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
  .then(response => response.json())
  .catch( e => reject(e) );

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

init();