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!