I have the following situation. I'm trying to create an object that will be initialized then reused over the course of a script. Part of the construction of such an object requires a login to retrieve data from a webpage. This data will be kept within the object.
Consider a file called myThingAbove.js
that contains this code:
module.exports = (function(){
//need to keep these updated
var a = {}, b = {};
const myThing = function(options){
somefun(args, function(err, resp){
//stuff
a = valueBasedOnResp;
b = valueBasedOnRespAsWell;
});
})
mything.prototype.myMethod = function(args) {
// makes use of a and b
}
return myThing;
})());
I'm initializing this "object" as follows:
const myThing = require('./myThingAbove.js');
const myObj = new myThing(args);
myObj.myMethod();
It looks like I'm not able to maintain a
or b
's state. The constructor call with the new
statement sets these values as expected but they do not persist with myObj
. How can I maintain the values of these variables within my instance of myObj
?
I'm using NodeJS v8.5.0.
UPDATE: It's been pointed out that myObj.myMethod()
and const myObj = new myThing(args);
will be executed asynchronously. This may actually be my problem. Is there a way to guarantee myObj
will be constructed before myObj.myMethod()
is called?