我需要同时打开多个WebSocket连接,然后在打开所有连接后执行操作。

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

这是我的代码:

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


我究竟做错了什么?

最佳答案

而不是将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();


很抱歉浪费大家的时间!

09-18 15:29