1

I am trying to get the values from axios get request that is in a function stored in another file postData.js

const BaseURL = 'http://127.0.0.1:8000/api/';

export const getData = (location) => {

  return axios.get(`${BaseURL}${location}`).then(res => res.data)
  .then((data) => {
    return data;
  })
}

From console.log(getData('menu/')), inside the component of other file I expect the values from the axios rather I am getting a promise object.

Hugo Dozois
  • 8,147
  • 12
  • 54
  • 58
pukar17
  • 13
  • 1
  • 4
  • Because a promise is asynchronous. When you log you do a synchronous operation on the function, and so you get what your function returned which is a Promise. That promise might eventually resolve to the data, but it's encapsulated into this asynchronous object. – Hugo Dozois Apr 17 '19 at 17:58
  • @pukar17 can you post the function in postData.js? – fedesc Apr 17 '19 at 17:59
  • 1
    Because network request is by its natural asynchronous. Axios returns promise cus it's the optimal way to represent the idea of "currently unresolved thing, but will, success or fail, eventually resolve". – hackape Apr 17 '19 at 18:03
  • `.then` always returns a promise. You cannot have an asynchronous process (network request) return a value synchronously. – Felix Kling Apr 17 '19 at 18:09

2 Answers2

1

Axios does return promise objects in order to deal with the asynchronicity of external API calls --> You wouldn't be able to predict the exact timing required to make your request as it is dependant of external factors. Thus you can use async / await and .then to handle its return.

Menoude
  • 101
  • 4
0

As per the git repo of AXIOS- Promise based HTTP client for the browser and node.js So it is returning a promise.

As axios implements XMLHttpRequests from the browser in a simpler way and XMLHttpRequests should be async in nature. So the promise is the best way to handle the scenarios. enter image description here

D Mishra
  • 1,518
  • 1
  • 13
  • 17