-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 ?

3
  • 1
    have you tried remove the 'await' from data to data = response.data, you already have a wait in the request Commented Aug 23, 2020 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. Commented Aug 24, 2020 at 3:41
  • @luis Thanks for suggestion but that did not make difference. Commented Aug 24, 2020 at 3:42

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.