如何在两个嵌套的' for'中进行同步调用? Node.JS中的循环:这是我的异步调用;我不知道如何拥有我的代码的同步版本,当create_db完成时,它会进入下一次迭代!
var new_items = [];
for (var key in config.models) {
var selected_field = config.models[key];
for (var item in config.models[key].fields) {
var selected_item = config.models[key].fields[item];
new_items.push({AttributeName: selected_item.name, AttributeType: selected_item.type});
}
CreateDB(selected_field.name, new_items);
var selected_item = config.models[key].fields[item];
}
EDDITED:在create_db中我使用回调函数!
function CreateDB(name, new_items) {
ddb.createTable(name, {hash: ['id', ddb.schemaTypes().number],
range: ['time', ddb.schemaTypes().string],
AttributeDefinitions: new_items
},
{read: 1, write: 1}, function(err, details) {
console.log("The DB is now created!");
});
}
由于
答案 0 :(得分:2)
您需要修改CreateDB
函数,以便进行回调,然后在.createTable
的回调中调用该回调:
function CreateDB(name, new_items, callback) {
ddb.createTable(name, {hash: ['id', ddb.schemaTypes().number],
range: ['time', ddb.schemaTypes().string],
AttributeDefinitions: new_items
},
{read: 1, write: 1}, function(err, details) {
console.log("The DB is now created!");
callback(err, details);
});
}
然后您可以使用async模块each method之类的内容。类似的东西:
var async = require('async');
async.each(Object.keys(config.models), function(key, callback) {
var new_items = [];
var selected_field = config.models[key];
for (var item in config.models[key].fields) {
var selected_item = config.models[key].fields[item];
new_items.push({AttributeName: selected_item.name, AttributeType: selected_item.type});
}
CreateDB(selected_field.name, new_items, callback);
}, function(err) {
// All done with CreateDB calls
});
答案 1 :(得分:1)
我建议使用async
模块。它具有实用功能,使我认为你想要做的事情非常容易。
async.each(Object.keys(config.models), function(key, done) {
var selected_field = config.models[key];
// I used the 'map' function to make it a bit easier to read
var new_items = selected_field.fields.map(function(item) {
return {
AttributeName: item.name
AttributeType: item.type
};
});
CreateDB(selected_field, new_items, done);
}, function(err) {
// this gets called when all db calls are finished
console.log("The DB is now created!");
});
function CreateDB(name, new_items, callback) {
ddb.createTable(name, {
hash: ['id', ddb.schemaTypes().number],
range: ['time', ddb.schemaTypes().string],
AttributeDefinitions: new_items
}, {
read: 1,
write: 1
}, callback);
}
答案 2 :(得分:0)