Axel
Axel

Reputation: 5111

How to implement Promise's then in async/await?

I have a following async/await method:

async todo() {
    const res = await axios.get('/todo')
}

getTodo() {
    this.todo()
}

Now, in async/await, how do you know that request is completed (200)? In Promises, we simply use then:

// store/todo.js
todo() {
    const res = axios({
        method: 'GET',
        url: '/todo'
    })
    return res
}

// components/Todo.vue
getTodo() {
    this.todo().then(res => {
        console.log('Request Executed Successfully!')
    })
}

This works perfectly but when I try to add async/await in getTodo and execute something like this:

async todo() {
    try {
      const res = await axios.get('/todo')
      return res
    } catch(e) {
      console.log(e)
    }
}

async getTodo() {
  try {
    await this.todo()
    console.log('Request Completed')
  } catch(e) {
    console.log(e)
  }
}

Demo: https://jsfiddle.net/jfn483ae/

It just doesn't work. The log gets executed before the request is completed i.e. after some error has occured. Please help.

Upvotes: 0

Views: 100

Answers (1)

Bergi
Bergi

Reputation: 664196

The log gets executed […] after some error has occured.

Yes, in your new todo method you catch the error and then return undefined as a normal result. Just don't use try/catch when you cannot handle the error, use the same code as you did orignally and the promise will work the same when you await it:

todo() {
  return axios({
    method: 'GET',
    url: '/todo'
  })
}
async getTodo() {
  try {
    await this.todo()
    console.log('Request Completed')
  } catch(e) {
    console.log(e)
  }
}

Upvotes: 2

Related Questions