Search code examples
vue.jsvue-resource

vue resource promise callback


Id like to parse a vue resource data and send callback request depending on the data i receive from server , how would i achive this either using Vue.interceptors or .then callback :

methods : function(){
var resource = this.$resource('index');
resource.save({name: 'jimmy'}).then(function (response) {
    //success callback
    //resend request lets say if response.data == 'test'

}, function (response) {
   // error callback
   console.log(response)
});
}

Solution

  • Simply do the call again and make sure you return the Promise created by it:

    methods: { someMethod: function(){
      var resource = this.$resource('index');
      resource.save({name: 'jimmy'})
        .then(function (response) {
    
          //resend request lets say if response.data == 'test'
          if (response.data === 'test') {
            // do request again and return the Promise.
            return resource.save({name: 'jimmy'})
          } else {
            return Promise.resolve(response)
          }
        })
        .then(function(response) {
          // do something with response
          // if there was a retry, `response` will be the second one.
        })
        .catch(function (error) {
    
        // catch() will catch any errors in the Promise chain, not just the first level.
          console.log(error)
        });
      }
    }