-1

iam traying to iterate over an array in js but it's not work and and i always get length equal 0 and when i try to access elements by index i get undefined but when i try to print my array by clg it worked well here is my code


function getData(url) {
    let arr = []
    fetch(url).then(response => response.json()).then(data => {
        for (let index = 0; index < data.length; index++) {
            arr[index] = data[index].content
        }
    })
        console.log(arr)
}

with console.log (arr) this the result

[]
0: "any"
1: "any"
2: "any"
3: "any"
length: 4
[[Prototype]]: Array(0)

but with console.log (arr[0]) i got

undefined

i want to get result from fetch and convert it to array and iterate over this array

  • 2
    fetch is *asynchronous* - so your `console.log(arr)` runs before the request is made - the reason you can see anything in the array though is because by the time you inspect it in the console, you've filled the array – Jaromanda X Aug 19 '22 at 08:37
  • 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) – Ben Fortune Aug 19 '22 at 08:40
  • jaromanda so i should mak delay ? or what – ahmed rashed Aug 19 '22 at 08:49

1 Answers1

0

You should return the Promise and the arr too. Then in a .then set the referenc you want.

function getData(url) {
  return fetch(url).then(response => response.json()).then(data => {
    let arr = [];
    for (let index = 0; index < data.length; index++) {
      arr[index] = data[index].content
    }
    return arr;
  })
}

getData(url).then(contents => { /*... do whatever you want */ });

You can use async/await, so itt will be easier to manage callbacks

async function getData(url) {
  return fetch(url).then(response => response.json()).then(data => data.map(d => d.content));
}

const contents = await getData(url);
for(const content of contents){
 /*... do whatever you want */ 
}
Totati
  • 1,489
  • 12
  • 23
  • is there is away to get array outside function to use it in all my program because those functions return promises not var – ahmed rashed Aug 19 '22 at 08:56