vue resource promise callback

Jimmy Obonyo Abor picture Jimmy Obonyo Abor · Apr 30, 2016 · Viewed 11.7k times · Source

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)
});
}

Answer

Linus Borg picture Linus Borg · May 1, 2016

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)
    });
  }
}