javascript - Making an array of object which have an asynchronous constructor -


i want following nodejs. make object array of following, each object has different local variables want when initialize.

obj.js

var obj = function (_id) {     this.id = _id;     var that=this;     db.getdata(_id,function(collection){ //this method 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 tasks arr 

but since arr constructor synchronous may not have data when calculations arr. how handle scenario ? want make sure objects created before doing work them.

thanks in advance.

guy, @mscdex said correct. firstly, in code, data shared in memory, should use this.data=[] in constructor. secondly, @mscdex said, move method prototype, say

obj.prototype.load=function(){     //code here... } 

then code below:

var obj = function(_id){     this.id=_id;     this.data = []; } obj.prototype.load = function(){     var = this;     db.getdata(this.id,function(collection){ //this method asynchronous         collection.toarray(function(err, items) {             that.data=items;         });     });     return that; } 

finally, question, how know of them ready.

obj.prototype.ready = []; obj.prototype.loaded=function(){     this.ready.push(1);     if(this.ready.length == obj.target)         obj.oncomplete(); } obj.notifyme = function(callback,len){     obj.target = len;     obj.oncomplete = callback; } 

the above code set array count load complete instances(use array because basic value not read instance's __proto__ reference). should add event(function) load, code @ last may following:

obj.prototype.load = function(){     var = this;     db.getdata(this.id,function(collection){ //this method asynchronous         collection.toarray(function(err, items) {             that.data=items;             that.loaded();         });     });     return that; } var args = [24,41,42]; obj.notifyme(function(){/*then tasks arr*/},args.length); var arr = args.map(function(arg){     return new obj(arg).load(); }); 

tell function notifyme callback work , number of instances. last problem if routine more 1 times should reset target , callback since obj global things.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -