Looping of promise array to retry websocket connection.

150 views
Skip to first unread message

Kai Yang Tay

unread,
Nov 14, 2014, 1:03:12 AM11/14/14
to ang...@googlegroups.com

"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?

Vivek Anand

unread,
Nov 15, 2014, 3:44:31 PM11/15/14
to ang...@googlegroups.com
Code in while loop is executed to create/define a method on promise resolution. promise.then() does not mean that the function in #then will be executed immediately.

Instead, while loop will run until either of the condition results in false. First condition will never return false. Second one will return false, once the code block in #then executed. This code block will be executed one the promise is resolved.

Hope it clarifies.
Reply all
Reply to author
Forward
0 new messages