AngularJS Services和并发访问全局变量

时间:2015-10-05 09:41:21

标签: javascript angularjs global-variables

我使用两个异步Web服务。我必须花时间添加响应中返回的每个对象。目标数据相同($ scope.time是全局变量)。我害怕在time = time + X一段时间或压垮。

$scope.time = 0;

$scope.elemAs = [];
$scope.loadElemA = function(nb) {
    ElemAService.query({nb: nb}, function(result) {
        $scope.elemAs = result;
        for (var index = 0; index < $scope.elemAs.length; index++) {
            $scope.time = $scope.time + $scope.elemAs[index].time;
        }
    });
};
$scope.loadElemA(2);

$scope.elemBs = [];
$scope.loadElemB = function(nb) {
    ElemBService.query({nb: nb}, function(result) {
        $scope.elemBs = result;
        for (var index = 0; index < $scope.elemBs.length; index++) {
            $scope.time = $scope.time + $scope.elemBs[index].time;
        }
    });
};
$scope.loadElemB(3);

console.log($scope.time);

在我的搜索结果中,我不确定获取$ scope.time = A0.time + A1.time + B0.time + B1.time + B2.time

在java中我使用同步的方法来执行任何线程的添加,但在javascript中我不知道该怎么做。

示例1:

(2)=&gt; $ scope.time = $ scope.time + $ scope.elemAs [0] .time; (2)

(4)=&gt; $ scope.time = $ scope.time + $ scope.elemAs [1] .time; (2)

(6)=&gt; $ scope.time = $ scope.time + $ scope.elemBs [0] .time; (2)

(8)=&gt; $ scope.time = $ scope.time + $ scope.elemBs [1] .time; (2)

10 )=&gt; $ scope.time = $ scope.time + $ scope.elemBs [2] .time; (2)

示例2:

(2)=&gt; $ scope.time = $ scope.time + $ scope.elemAs [0] .time; (2)

(4)=&gt; $ scope.time = $ scope.time + $ scope.elemBs [0] .time; (2)

(6)=&gt; $ scope.time = $ scope.time + $ scope.elemBs [1] .time; (2)

(8)=&gt; $ scope.time = $ scope.time + $ scope.elemAs [1] .time; (2)

10 )=&gt; $ scope.time = $ scope.time + $ scope.elemBs [2] .time; (2)

示例3:

(2)=&gt; $ scope.time = $ scope.time + $ scope.elemAs [0] .time; (2)

(4)=&gt; $ scope.time = $ scope.time + $ scope.elemBs [0] .time; (2)

(6)=&gt; $ scope.time = $ scope.time + $ scope.elemBs [1] .time; (2)同一时间 $ scope.time = $ scope.time + $ scope.elemAs [1] .time; (2)

8 )=&gt; $ scope.time = $ scope.time + $ scope.elemBs [2] .time; (2)

1 个答案:

答案 0 :(得分:0)

我的答案就是我的问题。我在每个回调中都有一个很大的循环。 javascript只有一个线程可用于所有回调。

var ShowCohort = React.createClass ({
  render: function() {
    return (
      <div className="container">
        <h3>Hello {this.props.cohort.name}</h3>
        <p>{this.props.cohort.description}</p>
      </div>
    )
  }
})

通过这个测试,我看到我有10.000 A和10.000 B或10.000 B和10.000 A.我从来没有混合使用A和B(AAABAABBA ...)

我的代码很好,我在回调中添加我没有问题