I’m struggling with the async flow of Node.js. Assume you have class below:
function myClass() {
var property = 'something';
var hasConnected = false;
this.connect = function(params) {
//Some logic that connects to db and in callback returns if the connection is successful
connectToSomeDB('ConnectionString', function(connectionResult) {
hasConnected = connectionResult
})
};
this.get = function(params) {
if(hasConnected) {
DoGetOperation() //
}
else {
//Another question. What should be done here. Call the connect again?
}
}
}
Considering the Javascript and Node structures I certainly believe there are some major issues with my design but I cannot figure a way out since connect must be called in order for any operation to work properly. But when I do some logging after the operations:
brandNewObject = myClass();
brandNewObject.connect();
brandNewObject.get();
I observe that the get function is called before obtaining the global isConnected variable. What can I do to make this work without actually going against the async structure of Node?
Ideally, the solution I’m looking for is actually to handle ‘connection’ internally instead of defining a callback ‘outer class’
There are different work-arounds for this.
One simple way is similar to what you are doing
Another method might be to use the same async callback mechanism for your get function, which would change your method signature to something like this.
HTH