2017-06-03 4 views
2

なぜq.allが2回目に動作しないのかわかりません。 2回目は、すべての約束が解決されるのを待つことはありません。

例を見て「コールサービス」ボタンを押してください。最初は両方の約束が解決するまで待つが、もう一度ボタンを押すとすぐに応答するが、なぜなのだろうか?

http://plnkr.co/edit/JNJmX1fjsmxrxYuiNHJb?p=preview

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

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

    $scope.Status1 = 'Waiting'; 
    $scope.Status2 = 'Waiting'; 
    $scope.buttonValue = "Call Services"; 

    $scope.doServices = function() { 

    $scope.Status1 = 'Waiting'; 
    $scope.Status2 = 'Waiting'; 
    $scope.buttonValue = "Working ..."; 
    console.log($scope.Status1) 

    var promise1 = MyService1.doIt(); 
    var promise2 = MyService2.doIt(); 

    $q.all([promise1, promise2]).then(
     function() { 
     $scope.Status1 = 'Done'; 
     }, 
     function() { 
     $scope.Status1 = 'Failed'; 
     } 
    ).finally(function() { 
     $scope.Status2 = 'Done waiting'; 
     $scope.buttonValue = "Call Services"; 
     //promises = null; 
    }); 

    } 

    $scope.callServices = function() { 
    $scope.Status1 = 'Waiting'; 
    $scope.Status2 = 'Waiting'; 
    $scope.doServices(); 
    } 

    $scope.reset = function() { 
    $scope.Status1 = 'Waiting'; 
    $scope.Status2 = 'Waiting'; 
    } 

}); 

app.service("MyService1", function($q, $timeout) { 

    var deferred = $q.defer(); 

    this.doIt = function() { 
    $timeout(function() { 
     console.log("Service 1 called!"); 
     deferred.resolve("Service 1 done!"); 
    }, 2000); 

    return deferred.promise; 
    } 
}); 


app.service("MyService2", function($q, $timeout) { 

    var deferred = $q.defer(); 

    this.doIt = function() { 
    $timeout(function() { 
     console.log("Service 2 called!"); 
     deferred.resolve("Service 2 done!"); 
    }, 5000) 

    return deferred.promise; 
    } 
}); 

答えて

2

約束は一度しか解決することができます。あなたのサービスは常に同じ約束を返します。解決したら解決します。

あなたはアンチパターンBTWを使用しています。 $ timeoutはすでに約束を返します。サービスに必要なものはすべて

app.service("MyService1", function($timeout) { 

    this.doIt = function() { 
    return $timeout(function() { 
     console.log("Service 1 called!"); 
     return "Service 1 done!"; 
    }, 2000); 
    } 
}); 

サービス2、BTWと同じです。しかし、両方のサービスが(タイムアウトの期間を除いて)まったく同じものになっているので、$ timeoutが何もしていないので、コントローラから$ timeoutを直接使うことができます。

+0

お返事ありがとうございます。私はq.allで遊んでいた。実際には私には複雑な問題があります。私はサーバー側のデータベース呼び出しを行う複数のサービス呼び出しを持っており、残りのコードを処理するために少なくとも2人は終了するのを待っています。だから私はサービスでシミュレートしていますが、私は両方の使用が問題を引き起こすと約束しているqとタイムアウトの二重の使用法だと思います。あなたの提案は問題を解決します。 – user1829319

関連する問題