Last active
March 25, 2018 10:12
-
-
Save hattmarris/8e18c337c386f2492ccb0a13633e4ad1 to your computer and use it in GitHub Desktop.
Fetch Async Await
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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