Array is empty after filling it in loop [duplicate] - javascript

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I'm dealing with a JSON response that is coming from an API. The ResponseJson contains information about a category; the responseJson.name contains a category name (tested in the console). Now I want to add all category names and store them in the empty array, categoryNames. After the for loop, the categoryNames turns out to be empty when I try to print it in the console, and I'm not sure what I'm missing. Here is the code:
_getCategories = item => {
const categoryNames = [];
for (let category of item.categories) {
fetch('http://54.168.73.151/wp-json/wp/v2/categories/' + category)
.then(response => response.json())
.then(responseJson => {
var categoryName = responseJson.name;
categoryNames.push(categoryName);
})
.catch(error => {
this.setState({
isLoading: false,
isError: true,
});
console.error(error);
});
}
console.log(categoryNames);
};
This questions has been identified as a possible duplicate of another question, but the answers are the other question is about a $ajax call, while I am trying to use pure JavaScript. Are there any solutions with this syntax?

_getCategories = item => {
const categoryNames = [];
let  fetches = [];
for (let category of item.categories) {
fetches.push(fetch('http://54.168.73.151/wp-json/wp/v2/categories/' + category));
}
Promise.all(fetches).then(res => {
/* do your stuff here */
})
};
You should you Promise.all to wait all fetches are done.
Can you try above code?

Related

Change order in function with fetch [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed last month.
Iam trying to render for Cars from my API. My problem is order in witch this fucntion is called.
export default function getGarage(arrayGarage) {
fetch('http://127.0.0.1:3000/garage')
.then(res => res.json())
.then(res => {
arrayGarage = res
console.log(arrayGarage)
})
if (arrayGarage) {
console.log(arrayGarage)
return arrayGarage
}
}
let arrayGarage = []
arrayGarage = getGarage(arrayGarage)
if (arrayGarage) {
console.log('before while')
for (let i = 0; i < arrayGarage.length; i++) {
console.log('in while')
createCar(arrayGarage[i])
}
}
In first step I got an empty Array (from IF console in fetch), in second step I got "before while" and in third step I got array with my Cars(form then console). How to do that my 'while' wait for property from fetch and handle while.
[]            apiFunctions.js:13
before while         garage.js:43
(4) [{…}, {…}, {…}, {…}]   apiFunctions.js:10

Why my nested object is create outside of itself? [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
console.log() async or sync?
(3 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 months ago.
Basically, when I try to create an Object and fill it with data from my Json file, the Object builds itself out of itself?
function fetchJson(name) {
var dico = {};
fetch('../json/' + name + '.json')
.then(response => response.json())
.then(data => {
for (var x in data) {
if(!isClubExist(dico, data[x].Club)) { // Just return if the club exist or not in the object
addClub(dico, data[x].Club);
}
addPlayer(dico, data[x].Club, data[x].Poste, fullName(data[x].Nom, data[x].Prénom));
}
})
return dico;
}
https://imgur.com/itBp1y4 (my result)
But when I try it by hand everything works fine.
var subjectObject = {
"Front-end": {
"HTML": ["Links", "Images", "Tables", "Lists"],
"CSS": ["Borders", "Margins", "Backgrounds", "Float"]
},
"Back-end": {
"PHP": ["Variables", "Strings", "Arrays"],
"SQL": ["SELECT", "UPDATE", "DELETE"]
}
}
console.log(subjectObject);
https://imgur.com/YCHYA8o (The type of result I need)
I'm new to JS and I would like to know what am I doing wrong.
fetch is asynchronous in nature. fetch will wait for the api response and let the code execution move ahead. Once the response is received, the script in the "then" block gets executed.
In this case, return dico gets executed first and then fetch receives the response from the api and makes the changes, hence the empty object.
You can return promise from your function like this
function fetchJson(name) {
return fetch('../json/' + name + '.json')
.then(response => response.json())
.then(data => {
var dico = {};
for (var x in data) {
if(!isClubExist(dico, data[x].Club)) { // Just return if the club exist or not in the object
addClub(dico, data[x].Club);
}
addPlayer(dico, data[x].Club, data[x].Poste, fullName(data[x].Nom, data[x].Prénom));
}
return dico;
});
}
And from where you call the function do this
fetchJson(name).then(dico => {
// do whatever....
});

Filtering a list of promises inside useEffect [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How can I access the value of a promise?
(14 answers)
Closed 7 months ago.
I found that it's not straight forward to filter a list of values of promises, so I tried the approach in this question (top answer).
The difference is, i'm using this inside useEffect in React.
My results array is empty outside of the async getData function:
// helper function
async function filter(arr, callback) {
const fail = Symbol();
return (
await Promise.all(arr.map(async (item) => ((await callback(item)) ? item : fail)))
).filter((i) => i !== fail);
}
useEffect(() => {
if (!stateData) {
let results = [];
async function getData() {
const res = await filter(data.slice(0, 5), async (item) => {
const boolRes = await myAsyncFunction(item);
return boolRes;
});
// results has data
results.push(...res);
}
getData();
console.log(results) // is empty, but results inside getData has data
}
}, []);
any idea how I can pull the data out of getData safely?

Use fetch() to read a JSON file and return an array with a function [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I prepared a function that reads a json file and I want to return an array that I can then use to create charts.
The function reads the file correctly and generates the array as intended within the fetch() function, but I am not able to pass it further. What I am doing wrong?
function getOrderDays(file, col){
const myRequest = new Request(file);
fetch(myRequest)
.then(response => response.json())
.then(data => {
var selecteddata = [];
data.forEach(function(item) {
selecteddata.push(parseInt(item[col]));
})
// Create an array containing the indexes of values > 0 :
var indexes = [0]; // I need a 0 at the beginning
var i = 0;
while (data[i]) {
if (selecteddata[i] != 0) {
indexes.push(i)
}
i++;
}
console.log(indexes); // This produces the result as needed
}).catch(err => console.error(err));
return indexes; // This is returning an empty array
}

I can print the values received from promise but cannot print its array.length [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
response screenshot image
I receive an array of values from JavaScript promise. When I console.log, I can print it's value. But cannot print its array.length. please see te comments in getImageUrl() method
public saveImages() {
for (let img of this.multipleImages) {
if (img.file) {
this.promise = this.FileUploadService.
addFile(img.file, img.randomName);
this.promise.then(result => {
this.setImageUrl(result);
});
}
}
}
setImageUrl(result) {
this.imageUrl.push(result);
}
getImageUrl() {
console.log(this.imageUrl.length, // length is always 0
this.imageUrl[0], //undefined
this.imageUrl); // has value (result from promise)
}
ngOninit() {
this.saveImages();//saves the image and calls the setImageUrl method.
this.getImageUrl();
}
when this.getImageUrl() is called, you can see what is print and what is not in the console.log of getImageUrl() method.
Try remove the for loop & skip overwriting your this.promise instance every iteration in that loop.
So, something like this:
const saveImages = () => Promise.all(this.multipleImages
.map(img => img && img.file ? this
.FileUploadService.addFile(img.file, img.randomName)
.then(this.setImageUrl.bind(this)) : null
))
// Then use with:
saveImages()
.then(() => this.getImageUrl())
Btw, here's where I'm working on these Promise ideas: https://github.com/justsml/escape-from-callback-mountain/

Categories