NodeJS在对象完成初始化之前继续执行

时间:2014-12-12 17:18:45

标签: node.js

我在节点中创建一个对象:

obj.push(new MyObject());

这是我的目标代码

function MyObject() {
    this.arr= [];
    for (x= 0; x< 2; x++) {
        this.arr.push([]);
        for (y= 0; y< 400; y++) {
            this.arr[x].push([]);
            for (z= 0; z< 1008; z++) {
                this.arr[x][y].push(0);
            }
        }
    }
}

在我调用obj.push后,程序执行继续,索引1006,1007的操作不起作用,因为我怀疑阵列没有完成初始化。如何在程序执行继续之前确保数组已初始化?

编辑:

for (i = 0; i < 1; i++) {

        (function(i) {
            asyncTasks.push(function(callback) {
                obj.push(new MyObject());
                some_class.bigOperation(obj[i], function() {
                    callback();
                });
            });
        })(i);
}

async.parallel(asyncTasks, function() {
    console.log("finished initializing");
});

2 个答案:

答案 0 :(得分:0)

不完全确定数组的含义是不是已初始化。您正在并行创建对象,这取决于您的实际实现可能是问题。看看这个版本,看看它是否有帮助。

var async = require('async');
var asyncTasks = [];
var obj = [];

function bigOperation(myObj, done) {
  setTimeout(function() {
    console.log('done with long operation');
    done();
  }, 1000);
}

function MyObject() {
  this.arr = [];
  for (x= 0; x< 2; x++) {
    var xlayer = [];
    this.arr.push(xlayer);
    for (y= 0; y< 400; y++) {
      var ylayer = [];
      xlayer.push(ylayer);
      for (z= 0; z< 1008; z++) {
        ylayer.push(0);
      }
    }
  }

  console.log('obj created');
}

for (i = 0; i < 10; i++) {
  var myObj = new MyObject();
  obj.push(myObj);

  (function(myObj) {
    asyncTasks.push(function(callback) {
      bigOperation(myObj, callback);
    });
  })(myObj);
}

console.log('starting async tasks');
async.parallel(asyncTasks, function() {
    console.log("finished initializing");
});

答案 1 :(得分:-1)

使用回调,节点是异步的,代码是逐行执行但不会等待

initialize = function(callback){
   var a = []; 
   //do your initialization here

   callback(a);
}

initialize(function(data){
   // array initialized you can now populate it.
});

然而,你循环对我来说有点奇怪。你确定它是正确的吗?