0

I have a script that fetches data from an API. I have 2 .then functions, one for parsing the function in a json and another for pushing the data into an array. But after that I can't loop over the values or access them whatsoever. I saw this question asked multiple times but none of the answers worked. Here s the code :

fetch(`${api_url}/${table_name}`)
    .then((response) => {
        return response.json();
    })
    .then((data) => {
        for(let row of data){
        response.push(row);
        }
    });

, where response is an empty array. So, how can I iterate through, aceess and modify the result array? Thanks in advance(Im losing my mind)

Andy Vavilov
  • 199
  • 1
  • 1
  • 7
  • "_So, how can I iterate through_" you are already iterating through `data` array here. What is the issue here? – palaѕн May 01 '20 at 14:03
  • "_modify the result array_" There is no `result` array in your code only `data` and `response`. Please explain what errors are you getting while accessing and modifying them in your main post. – palaѕн May 01 '20 at 14:05
  • 1
    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) – 3limin4t0r May 01 '20 at 14:33
  • Sorry, I meant how do I iterate and access elements of response. – Andy Vavilov May 01 '20 at 14:41
  • Ok, do you mean how you can access `response` outside `.then()` method? – palaѕн May 01 '20 at 14:48
  • Yes thats the problem i just cant figure out – Andy Vavilov May 01 '20 at 15:39

1 Answers1

0

You can use callback function in your then part. That callback function will parse your response and then you can iterate over response items. See example below.

_ajaxhelper.get(uri,
    (response) => { this.handleResponse(response); },
    (error) => { this.handleFailure(error); }));

handleResponse function:

private handleResponse(response: any) {
var items = this.parseData(response);
//Iteration over items
 }
Jayesh Tanna
  • 398
  • 5
  • 17