I have a node app that creates a SOAP client to make several API calls. Each call starts with a login() where a client is created. Rather than create a client for each successive call, I'd like to store it away and reuse the same client for those subsequent calls which happen in callbacks. What I'm struggling with is the scoping.
I have module.exports set to a function that returns an object:
return {
soapClient: null,
/**
* Establishes a connection with the client API & authenticates.
*
* @param {Object} args An object containing
* @param {Function} callback [description]
* @return {[type]} [description]
*/
login: function( username, password, callback ) {
var url = datasources.api.baseUrl;
// Create the SOAP client we'll use to call the API
datasources.api.module.createClient( url, function( err, soapClient ) {
// Store off the client for future calls.
// ---> THIS IS THE PROBLEM <--- //
this.soapClient = soapClient;
// Authenticate
var authArgs = {...};
soapClient.Login( authArgs, function( err, result ) {
// Authenticate
});
});
},
... ADDITIONAL FUNCTIONS ...
}
How can I properly store the soapClient that is passed to the createClient() callback so that it can be "cached" in the object property and reused by other functions in this model?