-1

I am Using Axios API to read/write from API Endpoints. An async function with an axios call returns some response(array). i can print that response(array) using console.log() but i want to access individual array element using subscript([]) but its failing every-time.

However when checking console logs on chrome, i can see response as an array but not able to use data at a particular index for further processing.

Below is the code :

  async function asyncFunc() {
  try {
    // fetch data from a url endpoint
    const response = await axios.get("https://jsonplaceholder.typicode.com/posts");
    data = await response.data;

    return data;
  } catch (error) {
    alert(error); // catches both errors
  }
}

var res = asyncFunc();
console.log("printing response");
console.log(res);

From above code i am getting response in form of an array with 100 elements. But i want to access elements at any particular index, i.e. '3' like console.log(res[3]); but i am not able to achieve that. is there any way to achieve that ?

kapil dev
  • 1
  • 1
  • 1
    have you tried remove the 'await' from data to data = response.data, you already have a wait in the request – luis Aug 23 '20 at 14:01
  • @jonrsharpe Thanks for the Pointer. I am New to JavaScript World did not know about Asynchronous nature of Axios Lib or JavaScript itself. Found a way to solve that issue by going through the link you have provided. – kapil dev Aug 24 '20 at 03:41
  • @luis Thanks for suggestion but that did not make difference. – kapil dev Aug 24 '20 at 03:42

1 Answers1

0

Was able to achieve that using below :

function foo() {
  // RETURN the promise
  return axios.get("https://jsonplaceholder.typicode.com/posts").then(function (response) {
    return response;
  });
}

var item = [];
var res = foo().then(function (response) {
  item.push(response.data[1]);
});
console.log(item);
kapil dev
  • 1
  • 1