2015-11-05 95 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

非常好!谢谢,将需要了解这一点,但是,这正是我想要的:) –