如何使用承诺的Socket.IO?

作为持续努力的一部分,我将目前的callback技术转变为使用blue-bird承诺库的承诺。

我想用Socket.IO来实现这个技巧。

  • 我怎样才能使用Socket.IO承诺而不是callback?
  • 有没有使用Socket.IO的标准方式? 任何官方解决scheme

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

Bluebird(和许多其他 承诺库)提供了帮助者方法来包装你的节点风格函数来返回一个承诺。

 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的函数。 返回的函数将返回一个承诺,其命运由给定节点函数的callback行为决定,而不是callback。 节点函数应该符合接受callback作为最后一个参数的node.js约定,并且将该错误作为第一个参数和第二个参数的成功值调用该callback。

看看这里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); }); }); });