【问题标题】:How can I use Socket.IO with promises?如何将 Socket.IO 与 Promise 一起使用?
【发布时间】:2014-12-25 17:22:15
【问题描述】:

作为持续努力的一部分,我正在使用blue-birdpromise 库将我当前的回调技术更改为promise。

我也想用 Socket.IO 实现这种技术。

  • 如何将 Socket.IO 与 Promise 一起使用而不是回调?
  • Socket.IO 有什么标准方法吗?有什么官方解决方案吗?

【问题讨论】:

标签: node.js socket.io promise


【解决方案1】:

您可以查看Q-Connection,它使用 Promise 作为远程对象的代理来促进 RPC,并且可以使用 Socket.IO 作为消息传输。

【讨论】:

    【解决方案2】:

    Bluebird(以及许多 other promise 库)提供了帮助方法来包装您的节点样式函数以返回一个承诺。

    var readFile = Promise.promisify(require("fs").readFile);
    
    readFile("myfile.js", "utf8").then(function(contents){ ... });
    

    https://github.com/petkaantonov/bluebird/blob/master/API.md#promisification

    返回一个将包装给定 nodeFunction 的函数。代替 接受回调,返回的函数将返回一个承诺,其 命运由给定节点函数的回调行为决定。 node 函数应符合 node.js 接受 a 的约定 回调作为最后一个参数,并调用带有错误的回调作为 第一个参数和第二个参数的成功值。

    【讨论】:

    • 当然,我知道,但我正在寻找对 socket.io/promises 的官方支持,例如 mongoose 的 exec(),它返回 Promise 对象。
    • 明白了。大多数 websocket 模块使用事件 API。将基于回调的 api 转换为 Promise 很容易,而使用 eventemitter 的东西则更少。
    【解决方案3】:

    看看这里https://www.npmjs.com/package/socket.io-rpc

    var io = require('socket.io').listen(server);
    var Promise = require('bluebird');
    var rpc = require('socket.io-rpc');
    
    var rpcMaster = rpc(io, {channelTemplates: true, expressApp: app})
            //channelTemplates true is default, though you can change it, I would recommend leaving it to true,
            //                   false is good only when your channels are dynamic so there is no point in caching
        .expose('myChannel', {
        //plain JS function
        getTime: function () {
            console.log('Client ID is: ' + this.id);
            return new Date();
        },
        //returns a promise, which when resolved will resolve promise on client-side with the result(with the middle step in JSON over socket.io)
        myAsyncTest: function (param) {
            var deffered = Promise.defer();
            setTimeout(function(){
                deffered.resolve("String generated asynchronously serverside with " + param);
            },1000);
            return deffered.promise;
        }
    });
    
    
    io.sockets.on('connection', function (socket) {
        rpcMaster.loadClientChannel(socket,'clientChannel').then(function (fns) {
            fns.fnOnClient("calling client ").then(function (ret) {
                console.log("client returned: " + ret);
            });
        });
    
    });
    

    【讨论】:

      猜你喜欢
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2017-08-23
      • 2011-09-17
      • 2012-12-21
      • 1970-01-01
      相关资源
      最近更新 更多