I'm trying to create a constructor function that includes a call to indexedDB or localStorage to retrieve some data if it exists and then populate it's values, either from the cache or the given (default) data.
I had it working, but somehow broke my code. Given that my method of programming is "hit it with a stick until it works", the code is an absolute mess. So I have simplified the problem down to a contrived example, which fails in the same way.
Removing the async function (setTimeout) fixes the problem, but then my code won't work.
var person = (function(){
function privateFn (value){
return value;
}
function private_asyncFn(value, callback){
setTimeout(function () {
return callback(value);
}, 10);
}
var DATA, NUM;
var personConstructor = function(name, age, gender, callback){
this.name = privateFn(name);
this.gender = privateFn(gender);
DATA = DATA || [];
NUM = NUM || 0;
this.num = NUM;
private_asyncFn(age, function(ret){
DATA[NUM++] = { name: this.name, age: ret };
if (callback instanceof Function) return callback(this.name);
}.bind(this));
};
personConstructor.prototype.getAge = function () {
if (this.gender === "male") return DATA[this.num].age;
else return DATA[this.num].age < 20 ? 18 : (Math.floor(DATA[this.num].age / 10) - 1) + "9 and holding";
};
return personConstructor;
})();
var name1;
var person1 = new person("jill", 32, "female", function(name){
name1 = name;
});
var age1 = person1.getAge(); //Uncaught TypeError: Cannot read property 'age' of undefined????
I see other code on SO using classes and promises and async/await, but I don't understand how that all works, so this code is a bit "old school", sorry about that.
In this example, can you retrieve the age of the person, immediately following the initialization of a new person?