I am using fetch()
command to get an array of data in JSON format. I am using function fetchURL()
to get data in JSON format. I use async-await
. Then in each data received I am trying to add it's login
field to an ordered list that I have created in the HTML file.
I have made a createListItem()
function to find the ordered list tag in the HTML file and append in it the login
field. But first I try to store all the login
fields in an array arr
. But I am not able to store the login
fields in it.
But when I directly use createListItem()
function to create a list item with login" field as text I am able to add these fields to the ordered list and hence I get the ordered list.
I am commenting out the lines that get me direct Output on the browser window when I do not store the login
fields in the arr
:
Code:
function createListItem(text) {
const parent = document.getElementsByTagName("ol");
const entry = document.createElement("li");
entry.textContent = text;
parent[0].appendChild(entry);
}
const url = "https://api.github.com/users ";
async function fetchURL() {
return (await fetch(url)).json();
}
let arr = [];
async function createList() {
const data = await fetchURL();
for (let i = 0; i < data.length; i ) {
//createListItem(`${data[i].login}`);
arr.push(data[i].login);
}
}
createList();
CodePudding user response:
you are getting the data in array, you need to create list after you call createList()
function:
createList().then(function(){
arr.forEach(element => {
createListItem(element);
});
});
you can also define arr
in the createList
function and return that then your code would be like this:
async function createList() {
let arr = [];
const data = await fetchURL();
for (let i = 0; i < data.length; i ) {
//createListItem(`${data[i].login}`);
arr.push(data[i].login);
}
return arr;
}
createList().then(arr=>{
arr.forEach(element => {
createListItem(element);
});
});
CodePudding user response:
You can achieve your objective with just one async function:
const url="http://jsonplaceholder.typicode.com/users";
async function getList(u){
const arr=(await fetch(u).then(r=>r.json())).map(e=>e.username);
document.querySelector("ol").innerHTML=arr.map(u=>`<li>${u}</li>`).join("");
console.log(arr);
}
getList(url);
<h2>List of login names</h2>
<ol></ol>
<p>end of page</p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
In the above snippet I used the public resource provided by typicode.com and extracted the property of username
instead of login
.