Returning Promises from Vuex actions

It is considered as a good practice to return a promise object from an action. In Vuex actions are asynchronous. If an action is complete , there is no way to detect that. You can return a Promise to let the calling function know that the action is complete. In the below example myAction returns a Promise. Then asynchronously makes a http call and resolves or rejects the Promise later.

actions: {
  
myAction(context, data) {
       return new Promise((resolve, reject) => {
           // Do something here... lets say, a http call using vue-resource
          
           this.$http("/api/something").then(response => {
               // http success, call the mutator and change something in state
              resolve(response);  // Let the calling function know that http is done. You may send some data back
          }, error => {
               // http failed, let the calling function know that action did not work out
              
                reject(error);
           })
       })
   }

When the Vue component initiates myAction it will get the Promise object back and it can know whether the action was successful or not.

export default {
   mounted: function() {
       // This component just got created. Lets fetch some data here using an action
      
       this.$store.dispatch("myAction").then(response => {
          
          console.log("Got some data, now lets show something in this component")
       }, error =>{
          
       console.error("Got nothing from server. Prompt user to check internet connection and try again")
       })
   }
}
The mutators are synchronous and they can change things in the state. They are normally called from actions.