How can I have Synchronous calls in two nested 'for' loops in Node.JS: Here is my Asynchronous call; I don't know how I can have synchronous version of my code, which goes to next iteration when create_db is done!
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: In create_db I'm using call back function!
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!");
});
}
Thanks
You're going to need to modify your CreateDB function so that it takes a callback and then call that callback in .createTables callback:
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);
});
}
Then you can use something like the async module's each method. Something like:
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
});
You might try something like Futures , most especially their sequence code, here : sequence
Hope this helps!
Edit: I believe you can also use a more built-in approach with es6-promise. However, I have no knowledge on this... :)
I would recommend using the async module. It has utility functions that make what I think you're trying to do really easy.
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);
}