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: []