user3421904
user3421904

Reputation:

ASYNC in Node.JS

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

Upvotes: 1

Views: 144

Answers (1)

Willem D'Haeseleer
Willem D'Haeseleer

Reputation: 20180

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);
}

Upvotes: 1

Related Questions