vue-realworld-example-app
vue-realworld-example-app copied to clipboard
use async-await for Promises
This might be somewhat subjective... but aside from syntax sugar for dealing with Promises... there are a few other benefits of using async-await over new Promise()
and .then
-
async
functions always return a Promise (regardless of returning a value or not) - no need to remember to callresolve()
- you can use traditional
try-catch-throw
for dealing with and reporting errors - no need to remember to callreject()
- for longer chains, you don't end up with a Christmas tree-shaped nesting and makes the code easier to reason about.
Here is an example from a code snippet taken from the auth module current
[REGISTER] (context, credentials) {
return new Promise((resolve, reject) => {
ApiService
.post('users', {user: credentials})
.then(({data}) => {
context.commit(SET_AUTH, data.user)
resolve(data)
})
.catch(({response}) => {
context.commit(SET_ERROR, response.data.errors)
})
})
future
async [REGISTER] (context, credentials) {
try {
const data = await ApiService
.post('users', {user: credentials})
context.commit(SET_AUTH, data.user)
return data;
} catch ({response}) {
context.commit(SET_ERROR, response.data.errors)
}
},
If this is something that needs to be done, I can work on it.
@techiedod Yes this would be an excellant improvement.
@morficus awesome ! And would you mind having a look at this issue : https://github.com/gothinkster/vue-realworld-example-app/issues/190 . I cannot find the meaning of using async/await
in it.