使用angularjs promises随机数相加

时间:2018-10-11 10:55:19

标签: javascript angularjs

app.service("service1",function($q,$timeout){
  this.number1 = function(num1) {
    var deferred = $q.defer();
    var result1 = Math.floor((Math.random()*5)+1);
    deferred.resolve(result1)
    return deferred.promise;
  }
});
app.service("service2",function($q){
  this.number2 = function(num2) {
    var deferred = $q.defer();
    //var num2=Math.floor((Math.random()*5)+1);
    var result2 = Math.floor((Math.random()*5)+1);
    // deferred.reject(0)
    deferred.resolve(result2)
    return deferred.promise;
  }
});
app.service("addservice",function($q){
  this.addition = function(num1 , num2) {
    var deferred = $q.defer();
    var result = num1+num2
    deferred.resolve(result)
    return deferred.promise;
  }
});
app.controller('myCtrl', function($scope, addservice,service1,service2,$q) {
 var p1 = service1.number1().then(function (data) {
  $scope.result1 = data;
  return data;
 });

 var p2 = service2.number2().then(function (data) {
  $scope.result2 = data;
  return data;
 });

$q.all([p1, p2]).then(function () {
 addservice.addition($scope.result1,$scope.result2)
.then(function (data) {
    $scope.result = data;
  })
});
});

如何使用$timeout,以便两个数字都在一段时间后出现?

以及如何对随机出现的大于5的数字使用deferred.reject()?我们只需要deferred.resolve()个小于5的数字即可。

1 个答案:

答案 0 :(得分:0)

app.service("service1",function($q,$timeout){
  this.number1 = function(num1) {
    var deferred = $q.defer();
    var result1 = Math.floor((Math.random()*5)+1);
    $timeout(function() {
       if (result1 > 5) {
          deferred.reject(result1);
       } else {
          deferred.resolve(result1);
       }
    }, 500);
    return deferred.promise;
  }
});
app.service("service2",function($q, $timeout){
  this.number2 = function(num2) {
    var deferred = $q.defer();
    //var num2=Math.floor((Math.random()*5)+1);
    var result2 = Math.floor((Math.random()*5)+1);
    // deferred.reject(0)
    $timeout(function() {
        if (result2 > 5) {
           deferred.reject(result2);
        } else {
           deferred.resolve(result2);
        }
    }, 100);
    return deferred.promise;
  }
});
app.service("addservice",function($q){
  this.addition = function(num1 , num2) {
    var deferred = $q.defer();
    var result = num1+num2
    deferred.resolve(result)
    return deferred.promise;
  }
});
app.controller('myCtrl', function($scope, addservice,service1,service2,$q) {
 var p1 = service1.number1().then(function (data) {
  $scope.result1 = data;
  return data;
 });

 var p2 = service2.number2().then(function (data) {
  $scope.result2 = data;
  return data;
 });

$q.all([p1, p2]).then(function () {
 addservice.addition($scope.result1,$scope.result2)
.then(function (data) {
    $scope.result = data;
  }, function(reason) {
     $scope.result = NaN
  }
});
});