I want to do the following with NodeJS. Make an object array of the following, where each object has different local variables where they want to get when they initialize.
obj.js
var Obj = function (_id) {
this.id = _id;
var that=this;
db.getData(_id,function(collection){ //this method is asynchronous
collection.toArray(function(err, items) {
that.data=items;
});
});
}
Obj.prototype.data = [];
module.exports = Obj;
app.js
var arr=[];
arr.push(new obj(24));
arr.push(new obj(41));
arr.push(new obj(24));
arr.push(new obj(42));
//then do tasks with the arr
But since the arr constructor is synchronous they may not have get all the data when I do calculations with the arr. So how to handle this scenario ? I want to make sure that all the objects are successfully created before doing any work with them.
Thanks in advance.
data
? It seems like you're usingdata
as a per-instance variable instead of one that's shared amongst allObj
instances.data
. Also, to makedata
a per-instance variable you can removeObj.prototype.data = [];
and just addthis.data = [];
right inside your constructor. Or maybe you can use that as your flag -- initially setthis.data = undefined;
then in your prototype functions do something like:if (!this.data) throw new Error('No data');