Node.JS中的ASYNC [英] ASYNC in Node.JS

查看:80
本文介绍了Node.JS中的ASYNC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

谢谢

推荐答案

这将是一种实现方法,很难,我不喜欢回调,我更喜欢使用包装它们或尝试修复问题.

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.

如果您要在内部for循环中执行异步操作,那么您将获得一些额外的异步重构乐趣.

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

这篇关于Node.JS中的ASYNC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆