Skip to content

Instantly share code, notes, and snippets.

@ehudthelefthand
Created March 22, 2021 09:08
Show Gist options
  • Save ehudthelefthand/cd860e927de1bc10cfd7e6ea925b35c0 to your computer and use it in GitHub Desktop.
Save ehudthelefthand/cd860e927de1bc10cfd7e6ea925b35c0 to your computer and use it in GitHub Desktop.
Post & Comment with Callback
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
ul {
list-style: none;
}
.title {
font-size: 20px;
font-weight: bold;
}
</style>
</head>
<body>
<ul id="content"></ul>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous"></script>
<script>
$.get('https://jsonplaceholder.typicode.com/posts', function(postData) {
let result = ''
let count = 0
let countComplete = postData.length
for (let i = 0; i < postData.length ; i++) {
console.log(i)
const post = postData[i]
$.get(`https://jsonplaceholder.typicode.com/posts/${post.id}/comments`, function(commentData) {
let commentElement = `<div>Comment of Post ID ${post.id}</div>`
for (let j = 0; j < commentData.length; j++) {
console.log(j)
const comment = commentData[j]
commentElement += `
<li>
<div class="comment-name">${comment.name}</div>
<p class="comment-email">${comment.email}</p>
<p class="comment-body">${comment.body}</p>
</li>
`
}
const postElement = `
<li>
<div class="title">${post.title} - ID ${post.id}</div>
<p class="body">${post.body}</p>
${commentElement}
</li>
`
// $('#content').append(postElement)
result += postElement
count++
if (count === countComplete) {
$('#content').html(result)
}
})
}
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment