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....
});
Related
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
This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 months ago.
I want to get a value from chrome.storage.local
var storage = chrome.storage.local;
authToken = storage.get('logintoken', function(result) {
var channels = result.logintoken;
authToken=result.logintoken;
console.log(authToken);
return authToken;
});
alert(authToken);
but out of the function authToken is undefined.
function getAllStorageSyncData(top_key) {
// Immediately return a promise and start asynchronous work
return new Promise((resolve, reject) => {
// Asynchronously fetch all data from storage.sync.
chrome.storage.local.get(top_key, (items) => {
// Pass any observed errors down the promise chain.
if (chrome.runtime.lastError) {
return reject(chrome.runtime.lastError);
}
// Pass the data retrieved from storage down the promise chain.
resolve(items);
});
});
}
Used this method and await like
var obj = await getAllStorageSyncData(['logintoken']);
and its worked
https://stackoverflow.com/a/72947864/1615818
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
}
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return values from async functions using async-await from function? [duplicate]
(3 answers)
Closed 3 years ago.
I'm trying to load a CSV file into my application at the beginning and keep the value in a variable and call it from other functions instead of accessing by then all the time
my code is
var DVizModule = (() => {
let dataset = [];
let _data = async () => {
const data = await d3.csv("data/alphabet.csv");
return data;
}
let data = _data().then(data => {
dataset = data;
return dataset;
})
return {
data: data
}
})();
console.log(DVizModule.data);
it returns
Promise pending proto: Promise
PromiseStatus: "resolved"
PromiseValue: Array(26)
When I write
const t = async function() {
const data = await d3.csv("data/alphabet.csv");
return data;
}
t().then(result => console.log(result))
it returns the file perfectly
I'm trying to access the file content via
DVizModule.data
If you want to access data synchronously, you should declare it as a plain value, not a promise. something like this should do the trick:
const DVizModule = {};
d3.csv("data/alphabet.csv").then(data => DVizModule.data = data);
Note, of course, that DVizModule.data will be undefined until the request is actually complete. If you want to ensure that the value actually is there, you will have to wrap the outer context into an async function and await the data at the very beginning. This way you can both ensure that the value is present when you code accesses it and use it in a synchronous manner.
Hope I got your question right and not trying to resolve the wrong problem ;)
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?