3

I want to save the json returned from axios into a variable. Currently I can only see it when I console.log(response.data) with the following code:

function status() {
  const url = "https://api.com";
  axios.get(url).then(function (response) {
    console.log(response.data);
  });
}
status(); // console.logs object successfully

If I just set response.data to a variable instead of logging it, it stays blank ( {} ). I want to do something like this:

let data = {};
function status() {
  const url = "https://api.com";
  axios.get(url).then(function (response) {
    data = response.data;
  });
}
status();
console.log(data); // {}
// I want to manipulate and use the properties of data in subsequent code here

How may I accomplish this please? Thank you for the help.

kylel9506
  • 71
  • 7
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Lewis Jul 31 '20 at 08:09
  • Not familiar with axios, but have you tried using async/await? It might be that the console.log() is firing before axios actually returns. – Matt Jul 31 '20 at 08:11
  • Also, it would probably be nicer to have the data be returned from the status() function. To do that, pop the data variable inside the function and return it after the axios call has finished. – Matt Jul 31 '20 at 08:13

3 Answers3

2

The function axios.get(url) returns a Promise. You can use async/await like so.

 async function status() {
  const url = "https://api.com";
  let response = await axios.get(url);
  return response.data;
}

status().then((data) => console.log(data));

5hifaT
  • 388
  • 2
  • 12
Rahul Bhobe
  • 2,815
  • 4
  • 11
  • 25
0

Axios executes an asynchronous operation. Any async operation always executes after all synchronous operations are executed. Read about JavaScript execution here: https://medium.com/@gaurav.pandvia/understanding-javascript-function-executions-tasks-event-loop-call-stack-more-part-1-5683dea1f5ec

Long story short, the console.log statement in the end is a sync operation which will always execute before axios(...).then callback.

JavaScript has a new feature however called async...await which allows you to run Promises in sequence like regular JavaScript statements. But please do note that it is still asynchronous execution in play.

async function status() {
  const url = "...";
  consr resp = await axios.get(url);
  return resp.data;
}

status().then(data => console.log(data));

In regular JavaScript this is equivalent to this:

function status() {
  const url = "...";
  return axios.get(url).then((resp) => {
    return resp.data;
  });
}

status().then(data => console.log(data));

Edit: To store an access data outside wrap everything inside a self executing async function and do the following:

(async () => {
  let data;
  function status() {
    const url = "...";
    return axios.get(url).then((resp) => {
      return resp.data;
    });
  }
  data = await status();
  console.log(data);
})();
Sachin Singh
  • 690
  • 1
  • 6
  • 14
  • Thanks. Not quite what I am looking for though. How can I save the data as a variable after the status.then() like this: ```let obj = {}; status().then((data) => (obj = data)); console.log(obj);``` – kylel9506 Jul 31 '20 at 08:56
  • It will be saved only once async operation is completed... You can only access the ``data`` inside the ``then`` callback. Not outside of it as in your case. – Sachin Singh Jul 31 '20 at 09:00
  • However, you can wrap your code in Self executing async function and use await on ``status`` function to solve your problem. Check my edit on the answer. – Sachin Singh Jul 31 '20 at 09:06
0

The axios.get(url) is an asynchronous method, which means it will not return the result but a Promise (an Object that means "It do not have the result, but I will get it eventually"). To get the result, you have to wait for it.

You have multiple options for that, the first one is using .then() (not really recommended)

axios.get(url).then((result) => {
  console.log(result);
});

The second one require using async/await. Async is used to define an asynchronous method, await is used to wait for an asynchronous method. You can only use await in an asynchronous method (as you.. well, have to wait).

const result = await axios.get(url);
console.log(result);

However, as said above, if you are in top module function (if you're not in a method for example, just right in your .js file), you can use immediately invoked function like this :

(async () => {
  const result = await axios.get(url);
  console.log(result);
)();

Et voilà !