Cant控制台日志阵列数据(从promise推送) [英] Cant console log array data (which was pushed from promise)

查看:43
本文介绍了Cant控制台日志阵列数据(从promise推送)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以基本上这是获取用户位置的代码,从Promise提取数据后,我无法在外部使用它,我尝试使用push数组对象,但无法使用其值.

So basically this is the code to get users' location, after fetching the data from Promise I can't use it outside, I tried using push array object but can't use its value.

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

推荐答案

问题是,当您调用google API(即您的 fetch 操作)时,需要花费几毫秒的时间才能完成.您下面的代码(在 fetch 回调之外)在提取调用完成之前 执行.这是一个正在发生的事的例子.

The problem is that when you call the google API (ie your fetch operation) it will take a few milliseconds to complete. Your code below (outside of your fetch callback) executes before the fetch call has finished. Here is an example of what is happening.

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);

请注意第二条日志如何在第一条日志之前发生.

Notice how the Second Log takes place before the First Log.

要解决此问题,您可以简单地移动逻辑,使其在回调中发生,因此直到 fetch 调用完成后才执行.另一种选择是使用 async/await

To fix this, you can simply move your logic so it takes place in your callback and therefore doesn't execute until the fetch call has finished. The other option is to use 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();

这篇关于Cant控制台日志阵列数据(从promise推送)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆