等待 Node 构造函数连接到 api 再发出命令

Posted

技术标签:

【中文标题】等待 Node 构造函数连接到 api 再发出命令【英文标题】:Wait for Node constructor to connect to api before issuing commands 【发布时间】:2014-10-31 21:29:45 【问题描述】:

对不起,如果问题的标题有点模棱两可,但我不完全确定如何措辞。

我正在编写一个与 json-rpc api 对话的 NPM 模块 - 这是当前设置。

// The module
function MyModule(config) 
    // do some connection stuff here
    connected = true


MyModule.prototype.sendCommand = function() 
    if(connected) 
        // do command
     else 
        // output an error
    


module.exports = MyModule;

// The script interacting with the module
var MyModule = require('./MyModule');
var config =  
    // config stuff 
;
var mod = new MyModule(config);
var mod.sendCommand;

命令不会发送,因为此时它还没有连接,我认为这是由于 NodeJS 的异步、非阻塞架构,我可能需要使用 Promise 来等待 API 的响应,我将在哪里实现这个?我是在我的模块中执行此操作,还是在与模块交互的脚本中执行此操作?

【问题讨论】:

不要在构造函数中连接 - 这是不礼貌的。如果您必须 - 对解决问题做出承诺,并在 sendCommand 之类的东西上执行thatPromise.then(function(),这样它总是会在结果解决后发送命令。您可能还对 kriskowal 的 q-connection 感兴趣。 【参考方案1】:

您将需要使用回调或承诺或类似的东西来指示连接何时完成,以便您可以在通过该回调启动的进一步代码中使用该连接。

虽然通常认为在构造函数中执行异步操作不是最佳实践,但可以这样做:

function MyModule(config, completionCallback) 
    // do some connection stuff here
    connected = true
    completionCallback(this);


var mod = new MyModule(config, function(mod) 
    // object has finished connecting
    // further code can run here that uses the connection
    mod.sendCommand(...);
);

更常见的设计模式是不将连接放在构造函数中,而是为此添加一个方法:

function MyModule(config) 


MyModule.prototype.connect = function(fn) 
    // code here that does the connection and calls
    // fn callback when connected


var mod = new MyModule(config);
mod.connect(function() 
    // object has finished connecting
    // further code can run here that uses the connection
    mod.sendCommand(...);
);

【讨论】:

【参考方案2】:

不要使用 Promise,使用节点的编程模型,您不会“调用函数”,而是“使用结果处理程序调用函数,以便在数据实际可用时处理数据”:

MyModule.prototype.sendCommand = function(handler) 
  if(connected) 
    // run stuff, obtain results, send that on:
    handler(false, result);
   else 
    // output an error, although really we should
    // just try to connect if we're not, and say
    // there's an error only when it actually fails.
    handler(new Error("ohonoes"));
  

然后你调用函数为

var MyModule = require('./MyModule');
var mod = ...
mod.sendCommand(function(err, result) 
  // we'll eventually get here, at which point:
  if (err)  return console.error(err); 
  run();
  more();
  code();
  withResult(result);
);

【讨论】:

以上是关于等待 Node 构造函数连接到 api 再发出命令的主要内容,如果未能解决你的问题,请参考以下文章

在 javascript/node.js 中连接到 Gmail IMAP API

来自连接到 Node.js API 的移动客户端的社交身份验证

Node.js - 以编程方式连接到 *** 或通过 *** 路由 HTTP 请求

如何从 Angular Nginx 容器连接到 Node API docker 容器

当我尝试连接到 mongodb 时出现这些错误

当我尝试连接到 mongodb 时出现这些错误