vue-realworld-example-app icon indicating copy to clipboard operation
vue-realworld-example-app copied to clipboard

use async-await for Promises

Open morficus opened this issue 7 years ago • 3 comments

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 call resolve()
  • you can use traditional try-catch-throw for dealing with and reporting errors - no need to remember to call reject()
  • 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)
    }
  },

morficus avatar Dec 21 '17 17:12 morficus

If this is something that needs to be done, I can work on it.

alexandru-dodon avatar Jan 09 '18 18:01 alexandru-dodon

@techiedod Yes this would be an excellant improvement.

vilsbole avatar Feb 03 '18 17:02 vilsbole

@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.

Allianzcortex avatar Sep 01 '19 22:09 Allianzcortex