Node.js函数在返回数据之前返回null /实现callback

对于Node.JS / Socket.io来说,这是非常新奇的事情,正确地实现一个callback会让我感到头疼。 熟悉JS / jQuery,但从来没有完全掌握jQuery实现之外创build自己的callback。

任何谁,我有一个类的构造函数,原型方法等工作正常处理静态数据,但是当我通过一个TCP套接字调用服务器(当然使用包装模块),我的函数返回null之前获取实际数据:

server.prototype.getStatus = function(){ var results = ""; this.conn.sendCommand('status', function(err, response){ if(err){console.error(err);return;} results = response['data']; /*Callback here - I'm trying to return the response message to the browser.*/ }); return results; }; 

这个函数适用于静态数据(例如results ='test'),但是,因为我必须连接到服务器才能得到消息,我需要实现一个callback函数(我假设…) – 我知道我在这里有不正确的开始。

对于我的“服务器”代码,正在使用以下内容:

  socket.on('get status', function(){ io.emit('status', server.getStatus()); }); 

这个方法当前也可以通过提交button触发。 当然,我的静态.html页面抓住了这个罚款:

  socket.on('status', function(msg){ alert(msg); $('#status').append(msg); }); 

因为我的函数是不正确的我被返回null – 我可以看到通过我的控制台返回的响应['数据'],当然,如果我login响应。 我不知道如何使getStatus()返回响应['data']而不阻塞任何东西 – 但是,基本上我试图从sendCommand返回到浏览器的响应。 我有困难

我正在使用的第三方模块可以在这里find: https : //github.com/dy-dx/node-rcon/blob/master/node-rcon.js

你只是把一个callback作为一个参数,也许是一个错误的参数等

 server.prototype.getStatus = function(callback){ this.conn.sendCommand('status', function(err, response){ if(err) { callback( err, null ); } else { callback( null, response['data'] ); } }); }; 

那么你使用它

 socket.on('get status', function(){ server.getStatus(function(err, data) { if (!err) { io.emit('status', data); } }); }); 

你甚至可以做

 server.prototype.getStatus = function(callback){ this.conn.sendCommand('status', callback); } 

 socket.on('get status', function(){ server.getStatus(function(err, data) { if (!err) { io.emit('status', data['data']); } }); });