Skip to content

Instantly share code, notes, and snippets.

@BrockReece
Last active February 1, 2018 17:08
Show Gist options
  • Save BrockReece/35429aa895aaf9972f79072425aaa7e4 to your computer and use it in GitHub Desktop.
Save BrockReece/35429aa895aaf9972f79072425aaa7e4 to your computer and use it in GitHub Desktop.
Promises vs AsyncAwait
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