How to return a promise from Vuex action in Vue.js

in Code Write a comment

In this tutorial, you’ll learn how to let the calling function know that the HTTP request succeeded or failed in Vue.js.

Let’s create a Vuex action that updates user profile.

actions: {
  UPDATE_PROFILE ({ commit, state }, { user }) {
    return new Promise((resolve, reject) => {
      axios.put(process.env.VUE_APP_BASE_URL + 'api/me', user, config).then(response => {
        // request succeeded
        resolve(response) // return response data to calling function
      }).catch(error => {
        // request failed 
        reject(error) // return error to calling function

As you can see UPDATE_PROFILE action returns a Promise. In Vuex actions are asynchronous, so the only way to know if the HTTP request succeeded or failed is to resolve or reject the promise.

To let the calling function know that the HTTP call succeeded and see the response data we add the following code:


If the call failed we can return the error message and let the calling function know that it failed:


If you find this post useful, please let me know in the comments below. 
Renat Galyamov

Want to share this with your friends?

PS: Make sure you check other Vue.js tutorials, e.g. how to set a default value for an HTML <select> tag in Vue.js or Top 5 CSS frameworks for your Vue.js project (2019).

I developed a Vue.js starter kit that you can order today

Order Vue.js starter kit

Write a Comment