本文介绍了使用angularjs Promise的随机数总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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 用于为 num2 传递 num1 service2 .Service3用于这些数字的总和.

service1 is used to pass num1 and service2 for num2. Service3 is used for the sum of those numbers.

如何在此处使用 $ q.all()来同步多个promise.?

How to use $q.all() here to sync multiple promises.?

推荐答案

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

You can use $q.all() method, it takes either an object or an array of promises and waits for all of them to resolve() or one of them to reject() and then executes the provided callback function.

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

这篇关于使用angularjs Promise的随机数总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 14:37