Last active
February 1, 2018 17:08
-
-
Save BrockReece/35429aa895aaf9972f79072425aaa7e4 to your computer and use it in GitHub Desktop.
Promises vs AsyncAwait
This file contains 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
export default { | |
methods: { | |
// better for readability | |
async veryReadable() { | |
const { data } = await axios.get(`https://jsonplaceholder.typicode.com/post/${response.data[0]}/comments?_page=1`) | |
this.comments = data | |
}, | |
// better for returning a promise for chaining | |
returningPromise() { | |
return axios.get('https://jsonplaceholder.typicode.com/comments?_page=1').then((response) => { | |
this.comments = response.data | |
}) | |
}, | |
// better for multiple unordered promises | |
multiplePromises() { | |
axios.get('https://jsonplaceholder.typicode.com/posts?_page=1').then((response) => { | |
this.posts = response.data | |
}) | |
axios.get('https://jsonplaceholder.typicode.com/comments?_page=1').then((response) => { | |
this.comments = response.data | |
}) | |
}, | |
// better when ordering promises | |
async orderedPromises() { | |
const response = await axios.get('https://jsonplaceholder.typicode.com/posts?_page=1') | |
const { data } = await axios.get(`https://jsonplaceholder.typicode.com/post/${response.data[0].id}/comments?_page=1`) | |
this.comments = data | |
}, | |
// works with try catch | |
async tryCatchMe() { | |
try { | |
const { data } = await axios.get('https://jsonplaceholder.typicode.com/post?_page=1') | |
this.comments = data | |
} catch (err) { | |
console.log(err) | |
} | |
}, | |
// better when debugging | |
async debugMe() { | |
const response = await axios.get('https://jsonplaceholder.typicode.com/posts?_page=1') | |
debugger // this will pause execution here | |
const { data } = await axios.get(`https://jsonplaceholder.typicode.com/post/${response.data[0]}/comments?_page=1`) | |
this.comments = data | |
}, | |
}, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment