使用angularjs的随机数总和保证

时间:2018-10-11 06:01:47

标签: javascript angularjs

app.service("service1", function ($q) {
    this.number1 = function (num1) {
        var deferred = $q.defer();
        var num1 = Math.floor((Math.random() * 5) + 1);
        var result1 = num1;
        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 = num2;
        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) {
    service1.number1().then(function (data) {
        $scope.result1 = data;
    })
    service2.number2().then(function (data) {
        $scope.result2 = data;
    })
    addservice.addition($scope.result1, $scope.result2).then(function (data) {
        $scope.result = data;
    });
});

service1用于传递num1的{​​{1}}和service2。 Service3用于这些数字的总和。

如何在此处使用num2来同步多个promise。?

2 个答案:

答案 0 :(得分:1)

您可以使用$q.all()方法,它接受一个对象或一个promise数组,然后等待它们全部到resolve()或其中一个到reject(),然后执行提供的回调函数。

//In $q as dependecies
app.controller('myCtrl', function ($scope, addservice, service1, service2, $q) {

    //Persist reference of promomise
    var p1 = service1.number1().then(function (data) {
            $scope.result1 = data;
        });
    //Persist reference of promomise
    var p2 = service2.number2().then(function (data) {
            $scope.result2 = data;
        });

    //Pass references
    $q.all([p1, p2]).then(function () {
        //Now pass result 1 and 2
        addservice.addition($scope.result1, $scope.result2).then(function (data) {
            $scope.result = data;
        })
    });
});

答案 1 :(得分:0)

您可以返回这两个值,并将它们用于已同步的promise:

app.controller('myCtrl', function($scope, addservice, service1, service2) {
  var promise1 = service1.number1().then(function(data) {
    $scope.result1 = data;
    return data;
  })
  var promise2 = service2.number2().then(function(data) {
    $scope.result2 = data;
    return data;
  })

  $q.all([promise1, promise2]).then(function(res) {
    addservice.addition(res[0], res[1]).then(function(data) {
      $scope.result = data;
    });
  })

});