0

I'm trying to write a function, which would be pull data in array, and then print them into condole. For right work for loop i'm using IIFE function for retrive all data consistently, but code not work correctly. Result is empty array: []. I think that my trouble due to the incorrect IIFE which i made. How I can fix this bug?

var url = [
  'http://www.json-generator.com/api/json/get/cevhxOsZnS',
  'http://www.json-generator.com/api/json/get/cguaPsRxAi',
  'http://www.json-generator.com/api/json/get/cfDZdmxnDm',
  'http://www.json-generator.com/api/json/get/cfDZdmxnDm',
  'http://www.json-generator.com/api/json/get/cfDZdmxnDm'
]

function fetchData(arg) {
  var urls = Array.isArray(arg) ? arg : [...arguments]
  var arr = [];
  for (var i = 0; urls.length < i; i++) {
    (function (i) {
      fetch(urls[i])
        .then(res => res.json())
        .then(res => arr.push(res))
    })(i)
  }
  return arr;
}

console.log(fetchData(...url))   // printed empty array: []
  • 2
    The problem is that fetch is *asynchronous*, so you are returning your array before any of the fetches have finished. [This question](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) may help. – CRice Jun 28 '18 at 20:44
  • Thanks for answer. That's right, fetch is asynchronous and for fix this feature i'm using IIFE function. And now I don't understand why it's not work correctly. – Алексей Мягков Jun 28 '18 at 20:51
  • 1
    Your IIFE is working fine. What is not working is that you are doing `console.log` before the results are fetched (remember? fetch is asynchronous, your code keeps running while the data is fetched) – blex Jun 28 '18 at 20:54
  • Of course! My fault, sorry. Thank you so much :) – Алексей Мягков Jun 28 '18 at 20:58
  • 1
    Here is how I would do it: https://codepen.io/anon/pen/oyQrNd?editors=0010#0 – blex Jun 28 '18 at 21:14
  • 1
    Your loop condition `urls.length < i` seems backwards. – kamoroso94 Jun 28 '18 at 21:19

0 Answers0