Please, help me with this code. It runs very slow, about 2 minutes. I’m new to js and don’t know how to improve it. I need to take data from multiple ajax requests and compare it. I tried to use for loops, $.map, but it works the same. What i’m doing wrong?
var user, post, image, comment;
$.when(
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(postData) {
post = postData;
},
}),
$.ajax({
url: "https://jsonplaceholder.typicode.com/comments",
success: function(commentData) {
comment = commentData;
},
}),
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function(userData) {
user = userData;
},
}),
$.ajax({
url: "https://jsonplaceholder.typicode.com/photos",
success: function(imageData) {
image = imageData;
},
}),
).then(function() {
$.each(post, function(index, postItem) {
$.each(comment, function(index, commentItem) {
$.each(user, function(index, userItem) {
$.each(image, function(index, imageItem) {
if (
postItem.id == commentItem.postId &&
postItem.id == imageItem.id &&
postItem.userId == userItem.id
) {
console.log(
"post title: " +
postItem.title +
" Post image: " +
imageItem.url +
" Author: " +
userItem.name +
" Comment: " +
commentItem.body
);
}
});
});
});
});
});
2
Answers
For the comments, users, and photos, transform the array of objects into a Map (or object), whose keys are the ids, and values are the values you want to extract from it later. Then loop over the posts, and from the ids in the post, look up the matching values on the Maps. If all 3 maps have a match, print the result.
Note that there’s no need for a large dependency like jQuery just to make a network request and iterate over an array – built-in JS methods works just fine:
Using my Mapper util, you can optimise it very fast. see the sample.
You can find script here:
https://gist.github.com/deepakshrma/4b6a0a31b4582d6418ec4f76b7439781