Node.js/Async-如何避免异步回调地狱? [英] Node.js/Async - How to avoid callback hell with async?

查看:108
本文介绍了Node.js/Async-如何避免异步回调地狱?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是后端的Node.Js和JavaScript Web开发的新手.我看到回调内部的回调可能会很痛苦,并且有一些模块可以避免这种情况.这些模块之一是异步的, https://github.com/caolan/async

I'm new to Node.Js and JavaScript web development on the backend. I see that callbacks inside callbacks could be a pain and there are modules to avoid that. One of these modules is async, https://github.com/caolan/async

我已经阅读了文档,但是很难开始并了解如何操作.

I've read the documentation but it is hard to start and understand how to do it.

例如,我有此功能"check_aut_user",如何使用异步方式转换此代码?

For example, I've this function "check_aut_user", How can I convert this code using async?

function check_auth_user(username, password, done) {

    var client = new pg.Client("pg://user:pass@127.0.0.1/database");
    client.connect(function(err) {
        // If not get the connection
        if(err) { return console.error('could not connect to postgres', err); }

        // Query the user table
        client.query('select * from "user" where username = $1 and password = $2', [username, password], function(err, result) {
            if(err) { return console.error('error running query', err); }

            if (result.rowCount > 0) {
                var res = result.rows[0];
                console.log(res);

                passport.serializeUser(function(res, done) {
                    //console.log("serializer: " + res);
                    done(null, res);
                });

                passport.deserializeUser(function(user, done) {
                    //console.log("deserializer: " + user['password']);
                    done(null, res);
                }); 

                return done(null, res);
            } else {
                return done(null, false);
            }               
        });     
    });
}

最好的问候,

推荐答案

有一些方法可以使用功能性编程技术来应对嵌套失控.我使用 curry 模块将循环主体分解为独立的例程;通常,与嵌套相比,这对性能的影响很小(为什么要研究curry).示例:

There are ways to combat runaway nesting using functional programming techniques. I use the curry module to break loop bodies out into stand-alone routines; usually this carries a very minor performance hit versus nesting (study curry for why). Example:

var curry = require('curry'),
    async = require('async');

var eachBody = curry(function(context, item, callback) {
  callback(null, context + item);  // first argument is error indicator
});

function exampleLoop(data, callback) {
  // use the curried eachBody instead of writing the function inline
  async.map(data, eachBody(data.length), callback);
}

function print(err, result) {
  console.log(result);
}

exampleLoop([2, 4, 6], print);  // prints [5, 7, 9]
exampleLoop([2, 4, 6, 7], print);  // prints [6, 8, 10, 11]

代替:

var async = require('async');

function exampleLoop(data) {
  async.map(data, function(item, callback) {
    callback(null, data.length + item);  
  }, function(err, result) {
    console.log(result);
  });
}

exampleLoop([2, 4, 6]);  // prints [5, 7, 9]
exampleLoop([2, 4, 6, 7]);  // prints [6, 8, 10, 11]

第二个示例更加紧​​凑,但是添加的嵌套越多,其可读性就越差.另外,通过拆分实现,您可以以多种方式重用组件功能,并且可以为单个组件功能编写单元测试,而不仅仅是为高级功能编写单元测试.

The second example is more compact, but the more nesting you add, the less readable it becomes. Also, by splitting up the implementation, you can reuse component functions in multiple ways, and you can write unit tests for the individual component functions, not only for the high-level functionality.

这篇关于Node.js/Async-如何避免异步回调地狱?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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