node.js和asynchronous模块错误

我在我的代码中得到一个未定义的variables,不知道我的代码中的错误是什么:

当我调用getClient时,我得到的客户端为undefined …我有一个肥皂客户端创build单身人士,我有:

var mySingleton = (function() { var soap = require('soap'); var async = require('async'); var instance; var client; function init() { var url = "http://172.31.19.39/MgmtServer.wsdl"; var endPoint = "https://172.31.19.39:9088"; var options = {}; options.endpoint = endPoint; async.series([ function(callback) { soap.createClient(url, options, function (err, result){ console.log('Client is ready'); client = result; client.setSecurity(new soap.BasicAuthSecurity('admin-priv', 'password')); callback(); }); } ], function(err) { if (err) return next(err); }); return { getClient : function() { console.log("I will give you the client"); **return client;** }, publicProperty : "I am also public", }; }; return { getInstance : function() { if (!instance) { instance = init(); } return instance; } }; })(); module.exports = mySingleton; 

所以我的消费者是:

 var soapC = mySingleton.getInstance(); var mySoapClient = soapC.getClient(); 

我得到mySingleton.client是未定义的。

为什么?

当然,有比这更好的解决scheme,但它表明,它可以更容易实现(没有asynchronous,没有单身):

 var soap = require('soap'); var client; var url = "http://172.31.19.39/MgmtServer.wsdl"; var options = { endpoint: "https://172.31.19.39:9088" }; module.exports = { getClient: function (callback) { if (client) { callback(null, client); return; } soap.createClient(url, options, function (err, result) { if (err) { callback(err); return; } console.log('Client is ready'); client = result; client.setSecurity(new soap.BasicAuthSecurity('admin-priv', 'password')); callback(null, client); }); }, publicProperty: "I am also public" }; 

而当使用客户端时:

 // using the client var mySoapServer = require('./path/to/above/code.js'); mySoapServer.getClient(function (err, client) { if (err) { /* to error handling and return */ } client.someRequestMethod(myEnvelope, function (err, response) { // ... }); }); 

如果您的Soap-Clients出现问题,可能会出现问题(错误时没有重新连接的逻辑)。 为此,您可以看看Redis客户端,MySQL客户端,MongoDB客户端的源代码…

编辑

对不同意见的一些评论:

Singleton模式在这里不需要。 节点将只执行一次这个JS文件,并且进一步require只获得对出口的引用。 没有必要创build一个IIFE范围 – variables将不会在外部可见,只有出口。

Node.js中的编程(除了一些特殊情况外)是一种全asynchronous的方式。 如果不这样做,它只是如果你有好运/运气不好,它只是不工作或失败/成功。

error handling看起来很像样板,但在大多数情况下是必须的。