2015-11-05 98 views
0

我有這個plunker來說明我的問題:

http://plnkr.co/edit/tsBy2K0xv6bboBlZRM8c

$scope.start = function() { 

    runThisUntil("Ok"); 
    //here I would like to do this: 
    //runThisUntil("Ok").then(function() { 
    //doSomeStuff() 
    //}); 

} 

$scope.clear = function() { 
    $scope.responses = []; 
} 

function runThisUntil(criteria) { 

    runThis(criteria); 



} 

function runThis(criteria) { 
    run().then(function (response) { 
    if (response == criteria) { 
     $scope.responses.push("Done"); 
    } else { 
     $scope.responses.push("Wait"); 
     runThisUntil(criteria); 
    } 
    }); 
} 


var okWhen = 10; 
var start = 0; 
function run() { 

    var deferred = $q.defer(); 
    $timeout(function() { 
    if (start !== okWhen) { 
    start += 1; 
    deferred.resolve("Bad"); 
    } else { 
    deferred.resolve("Ok") 
    start = 0; 
    } 
    }, 100); 


    return deferred.promise; 


} 
} 

我想在這裏模擬是循環的形式,在那裏我做請求到一個可以批量工作的http服務器,並在「工作完成」之前回答「還有更多的工作要做」。

當我試圖用承諾做到這一點時,我最終用$ q創建了新的延遲承諾,因此我等待解決的初始承諾從未得到解決,因爲請求被重複執行,而我通過執行相同的函數如果沒有完成,我再次進入。

- 編輯 我想我可以用$ scope。$ broadcast()完成這個工作,但是我希望儘可能使用$ q來解決這個問題,如果可能的話不要聽取事件。

回答

0

UPDATE:

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

angular.module('myApp').controller('TestCtrl', ["$timeout", "$interval", "$scope", "$q", function TestCtrl($timeout, $interval, $scope, $q) { 

    activate(); 

    $scope.responses = []; 

    function activate() { 

    $scope.start = function() { 

     runThisUntil("Ok").then(function() { 
     $scope.responses.push("Pushed final");; 
     }); 
    } 

    $scope.clear = function() { 
     $scope.responses = []; 
    } 

    function runThisUntil(criteria) { 

     return runThis(criteria); 
    } 

    function runThis(criteria) { 
     return run().then(function (response) { 
     $scope.responses.push("Done"); 
     }, function() { 
     $scope.responses.push("Wait"); 
     return runThis(criteria); 
     }); 
    } 


    var okWhen = 10; 
    var start = 0; 
    function run() { 

     var deferred = $q.defer(); 
     $timeout(function() { 
     if (start !== okWhen) { 
     start += 1; 
     deferred.reject("Bad"); 
     } else { 
     deferred.resolve("Ok") 
     start = 0; 
     } 
     }, 100); 

     return deferred.promise; 
    } 

    } 


}]); 

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

+0

你可以說明一個工作plunker?這不能運行runThis不會返回一個承諾 –

+0

我更新了我的答案 – yeouuu

+0

非常好!謝謝,將需要了解這一點,但是,這正是我想要的:) –