1

I'm kind of new to async in Node.JS and callbacks. Could you please let me know if this is the right way to have an async call?

function myFunc(schema) {
    async.each(Object.keys(schema), function(variable) {
        for (item in schema[variable]) {
            for (field in schema[variable][item]) {
                // Some operations go here                   
            }
            createDB(item, schema[variable][item]);
        }
    }); 
}


function CreateDB(name, new_items) {
    ddb.createTable(selected_field.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

5
  • 2
    Nope. your async.each iterator isn't executing the "done" argument and doesn't have a callback (making it relatively pointless) Commented Aug 7, 2014 at 20:24
  • 1
    What end result were you going for? only one createDB executing at a time? being able to know when their all created? Commented Aug 7, 2014 at 20:25
  • since it is table_create, I can have them simultaneously, it does not hurt and it is better in terms of performance Commented Aug 7, 2014 at 20:27
  • 1
    Do you need to know when it's done creating the databases? Commented Aug 7, 2014 at 20:28
  • Yes!... I prefer to know Commented Aug 7, 2014 at 20:29

1 Answer 1

1

This would be one way to do it, all tough I'm no fan of callbacks, I prefer to use promises.
This approach will just propagate all errors to the cb1, if you want to handle errors anywhere in between you should wrap them or try to fix stuff.

If you're gonna do async operations in that inner for loop you are in for some additional async refactor fun.

function myFunc(schema, cb1) {
    async.each(Object.keys(schema), function(variable, cb2) {
        async.each(Object.keys(schema[variable]), function(item, cb3) {
            for (var field in schema[variable][item]) {
                // Some operations go here
            }
            createDB(item, schema[variable][item], cb3);
        }, cb2);
    }, cb1);
}

function CreateDB(name, new_items, cb) {
    ddb.createTable(selected_field.name, {hash: ['id', ddb.schemaTypes().number],
            range: ['time', ddb.schemaTypes().string],
            AttributeDefinitions: new_items
        },
        {read: 1, write: 1}, cb);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.