I did an exercise (self-imposed) promise fetching some data from placeholder JSON files on https://jsonplaceholder.typicode.com/. The exercise in my opinion is finished, but I can't shake the feeling that the code is as dirty as code can be. Please check it out and point me into the right direction and tell me what I did wrong.
The exercise can be found here: http://codepen.io/kresimircoko/pen/vggPmJ
'use strict';
const root = 'https://jsonplaceholder.typicode.com/';
const postList = document.querySelector('#post-list');
console.clear();
const commentsPromise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.response);
};
xhr.onerror = reject;
xhr.open('GET', root + 'comments');
xhr.send();
});
const usersPromise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.response);
};
xhr.onerror = reject;
xhr.open('GET', root + 'users');
xhr.send();
});
const postsPromise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function() {
resolve(this.response);
};
xhr.onerror = reject;
xhr.open('GET', root + 'posts');
xhr.send();
});
// Posts
postsPromise
.then(data => {
const posts = JSON.parse(data); // Contains our posts
usersPromise
.then(data => {
const users = JSON.parse(data); // Contains our users
commentsPromise
.then(data => {
const comments = JSON.parse(data);
displayPosts(posts, users, comments);
});
});
}).catch(error => { console.log(error); });
// Users
function displayPosts(posts ,users, comments) {
let output = '';
posts.map(post => {
output += `
<li class="post">
<h4> ${displayUserName(users, post)} </h4>
<h3> ${post.title} </h3>
<p> ${post.body} </p>
<div class="comment-count"><span> ${displayCommentAmount(comments, post)} comments</span></div>
</li>
`;
});
postList.innerHTML = output;
}
function displayUserName(users, post) {
return users.map(user => {
if (user.id === post.userId) {
return user.name;
}
}).join('');
};
function displayCommentAmount(comments, post) {
const commentArray = comments.filter(comment => {
return comment.postId === post.id;
});
return commentArray.length;
}