-->

ASYNC中的Node.js(ASYNC in Node.JS)

2019-10-20 16:07发布

我有点新的Node.js和受回调异步。 能否请你让我知道,如果这是有一个异步调用的正确方法?

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

谢谢

Answer 1:

这将是做到这一点的一种方式,所有的艰难,我没有回调的球迷,我更喜欢使用的承诺 。
这种做法只会传播的所有错误的cb1 ,如果你想在你们之间应该随时随地处理错误包装它们或尝试修复的东西 。

如果你要在内部for循环做异步操作,你是在为一些额外的异步重构乐趣。

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


文章来源: ASYNC in Node.JS