简体   繁体   中英

Error handling in $q.all()

I'm using two factory calls in my controller. In both catches, I want to call separate functions to handle the errors.

what I have :

someFactory.functionOne().then(function (data) {
    $scope.one = data;
}).catch(functionToHandleOne());

someFactory.functionTwo().then(function (data) {
    $scope.two = data;
}).catch(functionToHandleTwo());

Is the any better way I can do this with $q.all() like

$q.all({
    one: someFactory.functionOne(),
    two: someFactory.functionTwo()
}).then (function (data) {
    $scope.one = data.one;
    $scope.two = data.two;
}).catch(
  //here I have to call functions functionToHandleOne() and functionToHandleTwo() according to error caused which function call
);

Your solution is perfectly fine. You are missing the error callback function in your 'catch' and the error argument of course.

An example:

$q.all({
    one: someFactory.functionOne(),
    two: someFactory.functionTwo()
}).then (function (data) {
    $scope.one = data.one;
    $scope.two = data.two;
}).catch(function(e){
 if(e.argument == 'error1')
  functionToHandleOne()();
 else
  functionToHandleTwo()();
});

var app = angular.module('plunker', []);

app.factory('json',function($q,$http){

  return function(files){

    var promises = files.map( function(file){

      var deffered  = $q.defer();

      $http({
        url : file,
        method: 'GET'
      }).
      success(function(data){
        deffered.resolve(data);
      }).
      error(function(error){
          deffered.reject();
      });

      return deffered.promise;

    })

    return $q.all(promises);
  }

});

app.controller('MainCtrl', function($scope,json) {
  $scope.name = 'World';

  json(['a.json','b.json']).then(function(datas){
    $scope.a = datas[0]
    $scope.b = datas[1]
  })

});

there in above full code you could find everything you needed. like

$q passed in factory and if you have multiple function there you can call all into single factory and make them really custom s your need.

you can see in controller as show in below code it will return datas.

  json(['a.json','b.json']).then(function(datas){
    $scope.a = datas[0]
    $scope.b = datas[1]
  })

"datas" returns multiple values of all calls so you need to use with array.

Please let me know if solve or need more research

khajaamin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM