我在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的子模型。并且因为异步var j将是data.length - 1用于所有回调。如何将索引参数传递给模型创建回调?
答案 0 :(得分: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
});
}
})();