2014-03-19 90 views
1

我在for語句創建模型:的NodeJS ORM2回調帶參數

for (var j = 0; j < data.length; j++) { 
     models.MyModel1.create({ name : data[j].name }, 
      function(err, model){ 
      if (err) { 
       throw err 
      } 
      models.OtherMyModel.create({ model_id : model.id, index : j }], 
       function(err,submodule){ 
      }); 
     }); 
     } 

所以在這裏我要創建子模型,將使用父模型ID和它的索引j。並且由於異步var j將data.length - 1用於所有回調。我如何將索引參數傳遞給模型創建回調?

回答

1

您可以使用承諾來實現這一點。
下面的片段使用when

var when = require('when'); 
var nodefn = require('when/node/function'); 
var promises = []; 

// Wrap model creation functions by a promise 
var createMyModel1 = nodefn.lift(models.MyModel1.create); 
var createOtherMyModel = nodefn.lift(models.OtherMyModel.create); 

for (var j = 0; j < data.length; j++) { 
    // Store the index into a local variable because when the first promise 
    // will resolve, `i` would be equal to `data.length`! 
    var index = j; 

    // Create the first model 
    var promise = createMyModel1({ 
    name: data[j].name 
    }).then(function(model) { 
    // Once the model is created, create the submodel 
    return createOtherMyModel({ 
     model_id: model.id, 
     index: index 
    }); 
    }, function(err) { 
    throw err; 
    }); 

    // Store the promise in order to synchronize it with the others 
    promises.push(promise); 
} 

// Wait for all promises to be resolved 
when.all(promises).then(function() { 
    console.log('All models are created'); 
}); 

另一種解決方案是使用yield和任何協程轉輪(可用自的node.js 0.11.x):

var co = require('co'); 

// Thunkify model creation functions 
var createMyModel1 = function(data) { 
    return function(fn) { models.MyModel1.create(data, fn); }; 
}; 

var createOtherMyModel = function(data) { 
    return function(fn) { models.OtherMyModel.create(data, fn); }; 
}; 

co(function *() { 
    for (var j = 0; j < data.length; j++) { 
    // Create first model 
    var model = yield createMyModel1({ 
     name: data[j].name 
    }); 

    // Create its submodel 
    var submodel = yield createOtherMyModel({ 
     model_id: model.id, 
     index: j 
    }); 
    } 
})();