Array Data Only Renders To Html Table Every Second Event, Otherwise Undefined
Solution 1:
You're calling renderData
before the fetch
completes so it hasn't finished fetching yet. Try moving it to inside the then
to see what I mean.
fetch
is asynchronous - it has to wait on a network response - and the code you have written inside the then
waits for it to complete, but the renderData
is being called right away, before that item has been pushed onto the array.
It seems like even with this change your code could be error prone if you are doing multiple fetches and pushing onto an array this way - the tags
could be pushed out of order and not match up with the names
as you might expect.
Solution 2:
Fetch and the chained thens will return a Promise object. you can push all of this into an array and use Promise.all() to check if all your fetches and thens are complete before calling renderData()
This sample code will guide you...
// Extract necessary values from returned object (language, name, latest tag) and push to corresponding arraysfunctionextractData() {
let psArr = [];
dataArr.forEach(i => {
names.push(i.full_name);
language.push(i.language);
let ps = fetch(i.tags_url)
.then(resp => {
return resp.json();
})
.then(resp => {
if (resp[0]) {
latestTag.push(resp[0].name);
} else {
latestTag.push(" ");
}
return resp;
});
psArr.push(ps);
// getLatestTag(i.tags_url);
});
Promise.all(psArr).then(()=>{
renderData();
});
}
It is important to note the when chaining then
s to a promise, the promise that is assigned to the variable is the promise of the last chained then
.
Also since this is all asynchronous the order can change depending on completion of the fetches, and this could result in unpredictable behavior.
Post a Comment for "Array Data Only Renders To Html Table Every Second Event, Otherwise Undefined"