r/javascript • • Jul 10 '16

The JavaScript language reboot is done

https://medium.com/@velmu/the-javascript-language-reboot-is-done-7bcec4be2cb6#.dy2fyy9j1
41 Upvotes

98 comments sorted by

View all comments

Show parent comments

24

u/[deleted] Jul 10 '16

Has anything really become simpler?

Are you kidding me?

fetch('https://jsonplaceholder.typicode.com/posts').then(response => {
	if (response.status === 200) {
		response.json().then(data => {
			const filteredPosts = data.filter(obj => obj.userId === 1);
			console.log(`You have made ${filteredPosts.length} posts.`);
		});
	}
});

vs

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
	if (xhttp.readyState == 4 && xhttp.status == 200) {
		var posts = JSON.parse(xhttp.responseText);
		
		var filteredPosts = [];
		for (var i = 0; i < posts.length; i++) {
			var post = posts[i];
			if (post.userId === 1) {
				filteredPosts.push(post);
			}
		}
		
		console.log('You have made ' + filteredPosts.length + ' posts.');
	}
};
xhttp.open("GET", "http://jsonplaceholder.typicode.com/posts", true);
xhttp.send();

0

u/[deleted] Jul 10 '16

[deleted]

4

u/konbit Jul 10 '16 edited Jul 10 '16

Here's my favorite:

async function getPosts() {
    const res = await fetch('https://jsonplaceholder.typicode.com/posts');
    const json = await res.json();
    const posts = json.filter(obj => obj.userId === 1);
    console.log(`You have made ${posts.length} posts.`);
}

EDIT: res.json() is a promise

1

u/TheLameloid Jul 10 '16

Is there a way to extract the result of the promise out of the .then() callback (which I assume is what the await keyboard does) without running into race conditions errors?

1

u/konbit Jul 10 '16

Nope. That's precisely why async await is so awesome.