1<script>
2function getFromAPI(url, callback){
3 var obj;
4 fetch(url)
5 .then(res => res.json())
6 .then(data => obj = data)
7 .then(() => callback(obj))
8 }
9
10getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);
11
12function getData(arrOfObjs){
13 var results = "";
14 arrOfObjs.forEach( (x) => {
15 results += "<p> Id: " + x.id + "<ul>"
16 Object.keys(x).forEach( (p) => {
17 results += "<li>" + (p + ": " + x[p]) + "</li>";
18 });
19 results += "</ul> </p> <hr>"
20 })
21 results += "";
22 document.getElementById("myDiv").innerHTML = results;
23}
24
25</script>
1async function getData(url) {
2 const response = await fetch(url);
3
4 return response.json();
5}
6
7const data = await getData(url);
8
9console.log({ data })
1function getData(url, cb) {
2 fetch(url)
3 .then(response => response.json())
4 .then(result => cb(result));
5}
6
7getData(url, (data) => console.log({ data }))
1function getFromAPI(url, callback){
2 var obj;
3 fetch(url)
4 .then(res => res.json())
5 .then(data => obj = data)
6 .then(() => callback(obj))
7 }
8
9getFromAPI('https://jsonplaceholder.typicode.com/posts', getData);
10
11function getData(arrOfObjs){
12 var results = "";
13 arrOfObjs.forEach( (x) => {
14 results += "<p> Id: " + x.id + "<ul>"
15 Object.keys(x).forEach( (p) => {
16 results += "<li>" + (p + ": " + x[p]) + "</li>";
17 });
18 results += "</ul> </p> <hr>"
19 })
20 results += "";
21 document.getElementById("myDiv").innerHTML = results;
22}