Change order in function with fetch [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 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

Related

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....
});

This function keeps returning undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Async Function leaving array blank outside of scope [duplicate]
(4 answers)
Closed 9 months ago.
I have started learning javascript recently and started a new project.
So my problem here is that have this call to an API, everything is good I can access to the names of the pokemons. But when I try to get a return it keep telling me is undefined. I have already try diferents solutions but nothings works.
Console of edge
function arrayOptions(pk) {
fetch('https://pokeapi.co/api/v2/pokemon?limit=10')
.then((res) => res.json())
.then((data) => {
for (let i = 0; i < data.results.length; i++) {
console.log(i, data.results[i].name);
pk.push(data.results[i].name);
}
});
return pk;
}
var pk = [];
pk = arrayOptions(pk);
console.log(pk[0]);

API Fetch - After storing response in key/value pairs in Object they are undefined [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)
Is Chrome’s JavaScript console lazy about evaluating objects?
(7 answers)
Closed 1 year ago.
I'm trying to build a Weather app.
I created an empty object to store certain data from the fetch response.
Then in my fetch function I store the data in key/value pairs.
When I console.log the weatherData variable it returns an object in my console but if I try to console.log a key/value of that object it returns undefined.
Any idea why they are undefined?
I've also tried
weatherData.hasOwnProperty('temp')
which returns false.
let weatherData = {};
function fetchWeather (city) {
fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=72c205fe50ec0c81fbf1577dbf8e83f0&units=metric`)
.then(response => {
return response.json();
}).then(response => {
weatherData.temp = response.main.temp;
weatherData.feels_like = response.main.feels_like;
weatherData.humidity = response.main.humidity;
weatherData.wind = response.wind.speed;
weatherData.description = response.weather[0].description;
})
.catch(error => {
console.log(error);
});
};

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
}

Array is empty after filling it in loop [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 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?

Categories