Search code examples
javascriptangularjsangular-promiseangularjs-service

call the same http request if it fails but with different parameter to get default data


does it make sense to call the same http request call within the catch if the first one fails but with different parameter in order to return some default data ?

var defaultData = false;

clientService.getClients(defaultData)
     .then(function (res) {

         //do something

      }).catch(function (err) {

          defaultData = true;

          clientService.getClients(defaultData)
                .then(function (res) {

                 //do something

                }).catch(function (err) {

                    console.log(err)

                });
      });

or this is a bad way ?


Solution

  • Be sure to return the new promise to the catch handler. The code will then chain properly and it avoids nesting:

    clientService.getClients({defaultData:false})
     .catch(function (err) {
    
        return clientService.getClients({defaultData: true})
    
    }).then(function (res) {
    
        //return something
    
    }).catch(function (err) {
    
        console.log(err)
        //IMPORTANT re-throw err
        throw err;
    
    });