作为持续努力的一部分,我正在使用blue-bird
promise库将我当前的回调技术改为承诺。
我也想用Socket.IO实现这个技术。
答案 0 :(得分:3)
您可以查看Q-Connection,它使用promises作为远程对象的代理来促进RPC,并且可以使用Socket.IO作为消息传输。
答案 1 :(得分:1)
Bluebird(以及许多other promise库)提供帮助方法来包装节点样式函数以返回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的函数。代替 接受回调,返回的函数将返回一个promise 命运由给定节点函数的回调行为决定。 节点函数应符合接受a的node.js约定 回调作为最后一个参数,并以错误形式调用该回调 第二个参数的第一个参数和成功值。
答案 2 :(得分:1)
看看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);
});
});
});