I need to open multiple WebSocket
connections concurrently and then perform actions once all the connections are opened.
I am using the defer()
, all()
, and then()
methods of RSVP.js. However, neither the then()
nor the catch()
is being triggered, and I cannot figure out where I am going wrong.
Here is my code:
var numberOfThreads = 6,
openSockets = function () {
var // the deferred object
d,
// array of promises
socketsOpened = [],
// websocket object and index
ws, i;
// open a new WebSocket connection for each iteration
for (i = 0; i < numberOfThreads; i += 1) {
// create deferred object
d = RSVP.defer();
// push promise into array
socketsOpened.push(d.promise);
// create websocket connection to valid, working socket server
ws = new WebSocket(url);
// websocket events
ws.onopen = function () {
// when socket is open, resolve deferred
d.resolve();
};
}
// when all connections are open, do stuff
RSVP
.all(socketsOpened)
.then(function () {
console.log('All sockets are opened!');
}).catch(function () {
console.log('Oops! Something has gone wrong!');
});
};
openSockets();
What am I doing wrong?
Instead of assigning the
deferred
tod
, I should create an array (d = []
), assign eachdeferred
to thei
position of the array (d[i] = RSVP.defer()
), and pushd[i]
into thesocketsOpened
array.Here's the new code:
Apologies for wasting everyone's time!