如何将 RSVP 延迟与 WebSocket 一起使用?

How do I use RSVP deferreds with WebSocket?

我需要同时打开多个 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();

抱歉浪费大家的时间!