如何在WebSocket中使用RSVP延迟?

时间:2015-06-01 12:51:32

标签: javascript websocket deferred rsvp.js

我需要同时打开多个Path : /var/www/html/jorani连接,然后在打开所有连接后执行操作。

我正在使用RSVP.js的WebSocketdefer()all()方法但是,then()then()都没有被触发,我无法弄清楚我哪里出错了。

这是我的代码:

catch()

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我应该创建一个数组(deferred),而不是将d分配给d = [],而是将每个deferred分配给数组的i位置(d[i] = RSVP.defer()),并将d[i]推送到socketsOpened数组。

这是新代码:

var numberOfThreads = 6,
    openSockets = function () {
        var // an array for deferred objects
            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) {
            // protect i with closure
            (function (i) {
                // create deferred object
                d[i] = RSVP.defer();

                // push promise into array
                socketsOpened.push(d[i].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[i].resolve();
                };
            }(i));
        }

        // 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();

为浪费每个人的时间而道歉!