0

i need to store position.coords.(latitude/longitude) inside an object declared outside of navigator.geolocation.getCurrentPosition().

async axiosRequest (usage) {
    var options = {}
    ...
    } else if (usage === 'gps') {
      navigator.geolocation.getCurrentPosition((position) => {
        options = {
          method: 'GET',
          url: 'https://api.waqi.info/feed/geo:' + position.coords.latitude + ';' + position.coords.longitude + '/',
          params: {
            token: process.env.VUE_APP_AICQN_API_KEY
          }
        console.log(options) // {...} that's work !!
        }
      });
      console.log(options) // {} ???
    }
    ...
    try {
      const response = await axios.request(options)
      return response.data
    } catch (error) {
      console.error(error)
    }
}

I don't understand why options is empty ( {} ) in the console.log(). How can I set options data inside the callback arrow function?

Thanks in advance!

2 Answers2

0

You already set the options data inside the callback, but it's wrong to try to console.log it this way, actually in your code, the second console.log will execute before the first one and the callback itself, you are calling Geolocation Browser API that works asynchronously and call the callback function after it's done, but first, js engine will resume the current execution context and finish all the calls in the stack,

Read more about:

Asyncrounouse JS,

Event Loop,

....

As a short answer, anything you need to do with the options immediately after setting the data, you need to do/call/trigger inside the callback:

async axiosRequest (usage) {
    var options = {}
    ...
    } else if (usage === 'gps') {
      navigator.geolocation.getCurrentPosition((position) => {
        options = {
          method: 'GET',
          url: 'https://api.waqi.info/feed/geo:' + position.coords.latitude + ';' + position.coords.longitude + '/',
          params: {
            token: process.env.VUE_APP_AICQN_API_KEY
          }
        };
   
        try {
          const response = await axios.request(options)
          ....
        } catch (error) {
          ....
        }
      });
    }
}

to be able to return a value from this function, I'd recommend you to change the structure of your code, you can wrap the getCurrentPosition in a promise, check this answer

Zac
  • 1,497
  • 9
  • 11
  • Thanks for the answer, but i have aniway the problem that i am inside a function.... If i return in the try { }, i return data outside callback function, but where did my data go? How can i store it inside options? Thanks for the answer, appreciated. – Pietro Tamburini Jan 24 '21 at 18:29
  • please check the answer that I've mentioned, also you can check the other answer on your question here, they are showing how can you wrap the API call in a promise, so you can use await to wait until it's done, then you can return from your function normally – Zac Jan 24 '21 at 18:31
  • You're right, << a promise>> I didn't understand what I had to do. I have resolved whit the Promise. – Pietro Tamburini Jan 24 '21 at 19:19
0

You can use a promise something like this:

import { request } from "axios";

const axiosRequest = async (usage) => {
  if (usage === "gps") {
    let getCurrentPositionOptions = new Promise((resolve, reject) => {
      navigator.geolocation.getCurrentPosition((position) => {
        const options = {
          method: "GET",
          url:
            "https://api.waqi.info/feed/geo:" +
            position.coords.latitude +
            ";" +
            position.coords.longitude +
            "/",
          params: {
            token: process.env.VUE_APP_AICQN_API_KEY
          }
        };
        return resolve(options);
      });
    });

    const options = await getCurrentPositionOptions;
    console.log(options);

    if (!options) return false;

    try {
      const response = await request(options);
      return response.data;
    } catch (error) {
      console.error(error);
    }
  }
};

You can see a working example here. You can read more about a Promise.

karavanjo
  • 1,626
  • 4
  • 18
  • 31