1

我在 for 语句中创建模型:

  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。并且由于 async var j 将 data.length - 1 用于所有回调。如何将索引参数传递给模型创建回调?

4

1 回答 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
    });
  }
})();
于 2014-03-19T15:04:19.540 回答