-->

ASYNC in Node.JS

2019-07-31 00:32发布

问题:

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

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