"use strict";

angular.module("socketExample",[])

.service("socketExampleService", ["$timeout", "$interval", "$q", 
                         function($timeout, $interval, $q){
 var sock = null;
var promises = [];
var cnt = 1;
 var initialize = function() {
 var deferred = $q.defer();
 $timeout(function(){
sock = new WebSocket("someWebSocketUrl");
 sock.onopen = function() {
console.log("Successful");
$interval(function(){
sock.send("");
}, 5000);
};
 sock.onmessage = function(event) {
// do something
}
 sock.onclose = function() {
console.log("closed");
};

sock.onerror = function(err) {
console.log("error");
};
 deferred.resolve(true);
} else {
deferred.reject(false);
}
 }, 1000);
 return deferred.promise;
}
 this.setup = function() {
promises[0] = initialize();
var exitLoop = false;
var maxRetries = 5;
        while(promises.length < maxRetries && !exitLoop) { // remove this 
while-loop - works!
    
        promises[promises.length - 1].then(function(result){
if(!result) 
promises[promises.length] = initialize();
                        else
                                exitLoop = true;
}, function(reason){
promises[promises.length] = initialize();
});
        }
}
}])

;


Hi I am trying to setup a websocket to auto retry connection. The reason of 
why I am doing this is because my "someWebSocketUrl" url is asynchronously 
retrieved from another XHR service.

I was thinking of controlling the retry by setting a set of promises[] 
array, so that if any one fufill the promise. The code will exit, and the 
websocket will be established.

But when I try to run this piece of code, my chrome browser crashed. 

When I remove the while-loop in setup(), it works. 

I do not understand why the code dun work when it starts to loop. Is it 
wrong to use promise this way?

-- 
You received this message because you are subscribed to the Google Groups 
"AngularJS" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/angular.
For more options, visit https://groups.google.com/d/optout.

Reply via email to