Skip to content

Instantly share code, notes, and snippets.

@hattmarris
Last active March 25, 2018 10:12
Show Gist options
  • Save hattmarris/8e18c337c386f2492ccb0a13633e4ad1 to your computer and use it in GitHub Desktop.
Save hattmarris/8e18c337c386f2492ccb0a13633e4ad1 to your computer and use it in GitHub Desktop.
Fetch Async Await
/* Async approach global namespace */
async function getData() {
return await fetch("https://jsonplaceholder.typicode.com/posts/1").then(response => response.json());
}
let data = {};
getData().then(d => data = d);
/* Class approach */
class Post {
constructor() {
this.data = {}
}
async getDataAsync() {
return await fetch("https://jsonplaceholder.typicode.com/posts/1").then(response => response.json());
}
getData() {
this.getDataAsync().then(d => this.data = d)
}
}
var post = new Post()
post.data; // {}
post.getData();
post.data; // "{"userId":1,"id":1,"title":"sunt aut facere repellat provident occaecati excepturi optio reprehenderit","body":"quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment