-1

I am pulling some data from a local API I made for testing, and need to use the resulting data outside of the function. I am new to JS and am having trouble working with Promises. Here is my code:

const axios = require('axios').default;

function price_data () {
    return axios.post('http://127.0.0.1:8000/api/token/', {
      username: 'parke',
      password: 'password'
    })
    .then(function (response) {
      var token = response['data']['access'];
      return axios.get('http://127.0.0.1:8000/price', {
      headers:{'Authorization': 'Bearer ' + token}
    })
      .then(function (response) {
        var all_data = []
        for (i = 0; i < response['data'].length; i ++) {
          all_data.push(response['data'][i]['close'])
        }
        console.log(all_data);
        return(all_data)
      })
      .catch(function (error) {
        console.log(error)
    })
    .catch(function (error) {
      console.log(error);
    })
    })
}
console.log(price_data())

The result looks like this:

Promise { <pending> }
[
       1,      1,      1,      1,      1,      1,      1, 1.5907,
  1.5318, 1.5318, 1.5907, 1.5907, 1.5907, 1.5907, 1.5907, 1.5318,
  1.3551,  1.414,  1.414,  1.414,  1.414, 1.3551, 1.2372, 1.2372,
   1.414,  1.414, 1.3551,  1.414,  1.414,  1.414,  1.414,  1.414,
   1.414,  1.414,  1.414,  1.414,  1.414, 1.2961, 1.2961, 1.2961,
   1.414,  1.414,  1.414,  1.414,  1.414, 1.3551, 1.3551, 1.3551,
  1.3551, 1.3551, 1.3551, 1.3551, 1.3551, 1.2961, 1.2961, 1.2961,
  1.2961, 1.2961, 1.2961, 1.2961, 1.3551, 1.2961, 1.2961, 1.3551,
   1.414,  1.414,  1.414, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729,
  1.4729,  1.414,  1.414,  1.414,  1.414,  1.414,  1.414,  1.414,
   1.414,  1.414, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729, 1.4729,
  1.4729, 1.4729, 1.5907, 1.5613, 1.5907, 1.5465,  1.576, 1.5318,
  1.5318, 1.5539, 1.5907, 1.5907,
  ... 1101 more items
]

I kinda understand that the function is returning before the console.log prints, but I need to get that data that is being logged outside of the function. It would be greatly appreciated if someone could help me out real quick. Thanks!

  • Just do `price_data().then(data => { /* do whatever you want with it in here */})`. Or you may prefer to use `async/await`. The key is that axios, and therefore your function, returns a Promise. – Robin Zigmond Jun 02 '20 at 18:44
  • read about async/await (promises) in JS because you need to understand them to understand your problem ;) to summary - this is not really axios issue – chojnicki Jun 02 '20 at 18:45
  • move your "all_data" variable up one level, immediately after the start of the block price_data func. Then return this value at the and of function. – Denys Levshenkov Jun 02 '20 at 18:47
  • 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) – zero298 Jun 02 '20 at 20:42

2 Answers2

0

You should use .then,

console.log(price_data()) // This will return promise
price_data().then((data) => {
console.log(data); // This will contain the final return value from the promise axios.then.
});
Ayushya
  • 1,862
  • 1
  • 10
  • 15
0

The thing with promises is that you cannot pull anything out of them, so every action with the response that you get by axios should be used with .then()

In your case it's price_data().then(data => console.log(data))

In the code above, you call price_data() function, which returns a promise with some data inside. After that you use .then(data => console.log(data)) to console that data

I hope it helps,

Cheers

EDIT: You can use async/await to assign data from promise to variable, but you will need to wrap your function into an async function like this:

async function getData (url) { // this is an async wrapping function
  function price_data () { // this is a function that you already have
    return axios(url)
  }
  const result = await price_data() // assign the data from price_data() to a varible using await 
  console.log(result) // console your variable
}

Here you can learn more on async/await

I really hope it will help you

  • Is there a way for me to set data to another variable so it can be used outside of any functions? My goal is really to just return the data, but when I return it even when I use price_data().then((data) => { it still gives me promise pending – Thomas Parker Jun 02 '20 at 20:10
  • Please, check my answer once again, I've edited it, so now it should answer your question – Leo Petliakov Jun 02 '20 at 20:34
  • @ThomasParker asynchronous code is a big stumbling block for many, I suggest you read the answers to [this question](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) which approach this common problem from just about every conceivable angle. – Robin Zigmond Jun 02 '20 at 20:41