【问题标题】:Callback hell in nodejs?nodejs中的回调地狱?
【发布时间】:2013-08-08 08:10:54
【问题描述】:

在下面的代码中我是在回调地狱吗?如何在不使用纯 javascript 中的任何异步模块的情况下克服这种情况?

emailCallBack(e_data, email);
if (email_list.length) {
  checkEmail(email_list.pop());
} else {
  completionCallback();
}

以上代码被复制到多个位置,以使代码按预期工作。

function processInviteEmails(email_list, user_id, emailCallBack, completionCallback){
      function checkEmail(email){
        try {
          check(email).isEmail();
          //is valid email
          checkConnected(email, user_id, function(connect_status, user_row, user_meta_row, connect_row){
            var e_data;
            //insert to connect and send msg to queue
            if(connect_status === 'not connected'){
              var cur_date = moment().format('YYYY-MM-DD');
              var dbData = {
                "first_name": '',
                "last_name": '',
                "email": email,
                "user_id": user_id,
                "status": "invited",
                "unsubscribe_token": crypto.randomBytes(6).toString('base64'),
                "created": cur_date,
                "modified": cur_date
              };
              ConnectModel.insert(dbData, function(result){
                if (result.insertId > 0) {
                  //send to email queue
                  //Queue Email
                  MailTemplateModel.getTemplateData('invitation', function(res_data){
                    if(res_data.status === 'success'){
                      var unsubscribe_hash = crypto.createHash("md5")
                        .update(dbData.unsubscribe_token + email)
                        .digest('hex');
                      var unsubscribe_link = app.locals.SITE_URL+'/unsubscribe/' + result.insertId + '/' + unsubscribe_hash;
                      var template_row = res_data.template_row;
                      var user_full_name = user_row.user_firstname+' '+ user_row.user_lastname;
                      var invitation_link = 'http://'+user_row.url_alias+'.'+ app.locals.SITE_DOMAIN;
                      var mailOptions = {
                        "type": 'invitation',
                        "to": dbData.email,
                        "from_name" : user_full_name,
                        "subject": template_row.message_subject
                          .replace('[[USER]]',  user_full_name),
                        "text": template_row.message_text_body
                          .replace('[[USER]]', user_full_name)
                          .replace('[[INVITATION_LINK]]', invitation_link)
                          .replace('[[UNSUBSCRIBE_LINK]]', unsubscribe_link),
                        "html": template_row.message_body
                          .replace('[[USER]]', user_full_name)
                          .replace('[[INVITATION_LINK]]', invitation_link)
                          .replace('[[UNSUBSCRIBE_LINK]]', unsubscribe_link)
                      };
                      mailOptions = JSON.stringify(mailOptions);
                      //send email to queue
                      sqsHelper.addToQueue(cfg.sqs_invitation_url, mailOptions, function(data){
                        if(data){
                          e_data = null;
                        }
                        else{
                          e_data = new Error('Unable to Queue ');
                        }
                        emailCallBack(e_data, email);
                        if (email_list.length) {
                          checkEmail(email_list.pop());
                        } else {
                          completionCallback();
                        }
                      });
                    }
                    else{
                      e_data = new Error('Unable to get email template');
                      emailCallBack(e_data, email);
                      if (email_list.length) {
                        checkEmail(email_list.pop());
                      } else {
                        completionCallback();
                      }
                    }
                  });
                }
                else{
                  e_data = new Error('Unable to Insert connect');
                  emailCallBack(e_data, email);
                  if (email_list.length) {
                    checkEmail(email_list.pop());
                  } else {
                    completionCallback();
                  }
                }
              });
            }
            else{
              e_data = new Error('Already connected');
              emailCallBack(e_data, email);
              if (email_list.length) {
                checkEmail(email_list.pop());
              } else {
                completionCallback();
              }
            }
          });
        } catch (e) {
          //invalid email
          emailCallBack(e, email);
          if (email_list.length) {
            checkEmail(email_list.pop());
          } else {
            completionCallback();
          }
        }
      }
      checkEmail(email_list.pop());
    }

【问题讨论】:

  • 为什么需要try/catch?通常,错误会传递给回调,这应该将缩进级别减少一半
  • 回答一半的问题:是的,您正处于回调地狱中。您可能想要引入一些抽象;如果您反对现有的控制流库,那么您可能至少想自己编写一个series 函数。

标签: node.js callback


【解决方案1】:

是的,您正处于回调地狱中。假设您不想使用 async 的解决方案(我怀疑您可以证明除偏见之外的合理性)包括:

1) 制作更多顶级函数。根据经验,每个函数应该执行 1 或 2 次 IO 操作。

2) 调用这些函数,使您的代码遵循由一小部分控制流“粘合”函数组织成业务逻辑的一长串短核心函数的模式。

代替:

saveDb1 //lots of code
  saveDb2 //lots of code
    sendEmail //lots of code

目标:

function saveDb1(arg1, arg2, callback) {//top-level code}
function saveDb2(arg1, arg2, callback) {//top-level code}
function sendEmail(arg1, arg2, callback) {//top-level code}
function businessLogic(){//uses the above to get the work done}

3) 使用更多的函数参数而不是过多地依赖闭包

4) 发出事件并解耦你的代码!看看您是如何将代码嵌套到数据库中,然后构建电子邮件并将其添加到队列中的?难道你没有看到这两个不需要一个在另一个之上存在吗?电子邮件非常适合用于发送事件的核心业务逻辑以及侦听这些事件和排队邮件的电子邮件模块。

5) 将应用级服务连接代码与特定事务业务逻辑解耦。处理与网络服务的连接应该更广泛地处理,而不是嵌入特定的业务逻辑集。

6) 阅读其他模块的示例

至于你是否应该使用异步库,你可以而且应该自己决定,但是之后你知道并且非常了解这些方法中的每一种:

  1. 回调和基本的函数式 JavaScript 技术
  2. 事件
  3. 承诺
  4. 辅助库(异步、步进、灵活等)

任何认真的 node.js 开发人员都知道如何在所有这些范例中使用和工作。是的,每个人都有自己喜欢的方法,也许对不喜欢的方法有些书呆子气,但这些都不难,而且如果不能指出你从头开始编写的一些非平凡的代码,就下定决心做出决定是很糟糕的每个范式。此外,您应该尝试几个帮助程序库并了解它们的工作原理以及它们为什么会为您节省样板文件。研究 Tim Caswell 的 Step 或 Caolan McMahon 的 async 的工作会很有启发性。你见过everyauth 源代码对promise 的使用吗?我个人不喜欢它,但我必须承认作者已经从该库中挤出了几乎所有重复的内容,他使用承诺的方式会将你的大脑变成椒盐脆饼。这些人是有很多要教的巫师。不要仅仅为了时髦点或其他什么而嘲笑那些图书馆。

callbackhell.com 也是一个不错的外部资源。

【讨论】:

  • 我想我应该使用异步库。
  • 很高兴知道如何使用简单的回调而不陷入困境。然后学习如何使用基本事件来获得类似的结果。然后考虑承诺。但最终在编写 Web 应用程序时,每个请求通常涉及 3 个或更多需要串行或并行完成的 I/O 操作,是的,您可能想学习如何使用控制流库,例如 async、nimble、步骤,或类似的。
  • 您好,在这种情况下我应该使用 async.series 还是 async.waterfall?
  • 我有一个论点,为什么我不使用异步或其他辅助库,例如下划线或承诺。对于我来说,这 3 个库正在污染代码。 Vanilla js 简单、容易,你不需要使用黑盒函数来运行“并行”异步函数,你只需要了解这些东西是如何工作的。如果你组织你的代码,你就不需要黑盒子来做这样简单的事情。
  • @askkirat 以serieswaterfall 开头,因为它们更容易理解。最终,当您了解您的操作之间真正的依赖关系或缺乏依赖关系时,您可以切换到 parallel 并可能加快一些事情的速度。
【解决方案2】:

“如果你尝试使用纯 node.js 编写商业数据库登录,你会直接进入回调地狱”

我最近创建了一个名为 WaitFor 的简单抽象,用于在同步模式下调用异步函数(基于 Fibers):https://github.com/luciotato/waitfor

查看数据库示例:

数据库示例(伪代码)

纯 node.js(温和的回调地狱):

var db = require("some-db-abstraction");

function handleWithdrawal(req,res){  
    try {
        var amount=req.param("amount");
        db.select("* from sessions where session_id=?",req.param("session_id"),function(err,sessiondata) {
            if (err) throw err;
            db.select("* from accounts where user_id=?",sessiondata.user_ID),function(err,accountdata) {
                if (err) throw err;
                    if (accountdata.balance < amount) throw new Error('insufficient funds');
                    db.execute("withdrawal(?,?),accountdata.ID,req.param("amount"), function(err,data) {
                        if (err) throw err;
                        res.write("withdrawal OK, amount: "+ req.param("amount"));
                        db.select("balance from accounts where account_id=?", accountdata.ID,function(err,balance) {
                            if (err) throw err;
                            res.end("your current balance is "  + balance.amount);
                        });
                    });
                });
            });
        }
        catch(err) {
            res.end("Withdrawal error: "  + err.message);
    }  

注意:上面的代码虽然看起来会捕获异常,但不会。 用回调地狱捕获异常会增加很多痛苦,我不确定你是否会有'res'参数 回应用户。如果有人想修改这个例子……做我的客人吧。

使用 wait.for

var db = require("some-db-abstraction"), wait=require('wait.for');

function handleWithdrawal(req,res){  
    try {
        var amount=req.param("amount");
        sessiondata = wait.forMethod(db,"select","* from session where session_id=?",req.param("session_id"));
        accountdata= wait.forMethod(db,"select","* from accounts where user_id=?",sessiondata.user_ID);
        if (accountdata.balance < amount) throw new Error('insufficient funds');
        wait.forMethod(db,"execute","withdrawal(?,?)",accountdata.ID,req.param("amount"));
        res.write("withdrawal OK, amount: "+ req.param("amount"));
        balance=wait.forMethod(db,"select","balance from accounts where account_id=?", accountdata.ID);
        res.end("your current balance is "  + balance.amount);
        }
    catch(err) {
        res.end("Withdrawal error: "  + err.message);
}  

注意:将按预期捕获异常。 db 方法(db.select、db.execute)将使用 this=db 调用

您的代码

为了使用wait.for,你必须标准化你的回调函数(错误,数据)

如果您标准化您的回调,您的代码可能如下所示:

//run in a Fiber
function processInviteEmails(email_list, user_id, emailCallBack, completionCallback){

    while (email_list.length) {

      var email = email_list.pop();

      try {

          check(email).isEmail(); //is valid email or throw

          var connected_data = wait.for(checkConnected,email,user_id);
          if(connected_data.connect_status !== 'not connected') throw new Error('Already connected');

          //insert to connect and send msg to queue
          var cur_date = moment().format('YYYY-MM-DD');
          var dbData = {
            "first_name": '',
            "last_name": '',
            "email": email,
            "user_id": user_id,
            "status": "invited",
            "unsubscribe_token": crypto.randomBytes(6).toString('base64'),
            "created": cur_date,
            "modified": cur_date
          };

          result = wait.forMethod(ConnectModel,'insert',dbData);
          // ConnectModel.insert shuold have a fn(err,data) as callback, and return something in err if (data.insertId <= 0) 

          //send to email queue
          //Queue Email
          res_data = wait.forMethod(MailTemplateModel,'getTemplateData','invitation');
          // MailTemplateModel.getTemplateData shuold have a fn(err,data) as callback
          // inside getTemplateData, callback with err=new Error('Unable to get email template') if (data.status !== 'success') 

          var unsubscribe_hash = crypto.createHash("md5")
            .update(dbData.unsubscribe_token + email)
            .digest('hex');
          var unsubscribe_link = app.locals.SITE_URL+'/unsubscribe/' + result.insertId + '/' + unsubscribe_hash;
          var template_row = res_data.template_row;
          var user_full_name = user_row.user_firstname+' '+ user_row.user_lastname;
          var invitation_link = 'http://'+user_row.url_alias+'.'+ app.locals.SITE_DOMAIN;
          var mailOptions = {
            "type": 'invitation',
            "to": dbData.email,
            "from_name" : user_full_name,
            "subject": template_row.message_subject
              .replace('[[USER]]',  user_full_name),
            "text": template_row.message_text_body
              .replace('[[USER]]', user_full_name)
              .replace('[[INVITATION_LINK]]', invitation_link)
              .replace('[[UNSUBSCRIBE_LINK]]', unsubscribe_link),
            "html": template_row.message_body
              .replace('[[USER]]', user_full_name)
              .replace('[[INVITATION_LINK]]', invitation_link)
              .replace('[[UNSUBSCRIBE_LINK]]', unsubscribe_link)
          };
          mailOptions = JSON.stringify(mailOptions);
          //send email to queue ... callback(err,data)
          wait.forMethod(sqsHelper,'addToQueue',cfg.sqs_invitation_url, mailOptions); 

      } catch (e) {
          // one of the callback returned err!==null 
          emailCallBack(e, email);
      }

    } // loop while length>0

    completionCallback();

  }

  // run the loop in a Fiber (keep node spinning)
  wait.launchFiber(processInviteEmails,email_list, user_id, emailCallBack, completionCallback);

看到了吗?没有回调地狱

【讨论】:

    【解决方案3】:

    我在my blog 中添加了另一个解决方案。它很丑,但它是我用纯 javascript 可以做的最易读的事情。

    var flow1 = new Flow1(
        {
            execute_next_step: function(err) {
                if (err) {
                    console.log(err);
                };
            }
        }
    );
    
    flow1.execute_next_step();
    
    function Flow1(parent_flow) {
        this.execute_next_step = function(err) {
            if (err) return parent_flow.execute_next_step(err);
            if (!this.next_step) this.next_step = 'START';
            console.log('Flow1:', this.next_step);
            switch (this.next_step) {
                case 'START':
                    this.next_step = 'FIRST_ASYNC_TASK_FINISHED';
                    firstAsyncTask(this.execute_next_step.bind(this));
                    break;
                case 'FIRST_ASYNC_TASK_FINISHED':
                    this.firstAsyncTaskReturn = arguments[1];
                    this.next_step = 'ANOTHER_FLOW_FINISHED';
                    this.another_flow = new AnotherFlow(this);
                    this.another_flow.execute_next_step();
                    break;
                case 'ANOTHER_FLOW_FINISHED':
                    this.another_flow_return = arguments[1];
                    this.next_step = 'FINISH';
                    this.execute_next_step();
                    break;
                case 'FINISH':
                    parent_flow.execute_next_step();
                    break;
            }
        }
    }
    
    function AnotherFlow(parent_flow) {
        this.execute_next_step = function(err) {
            if (err) return parent_flow.execute_next_step(err);
            if (!this.next_step) this.next_step = 'START';
            console.log('AnotherFlow:', this.next_step);
            switch (this.next_step) {
                case 'START':
                    console.log('I dont want to do anything!. Calling parent');
                    parent_flow.execute_next_step();
                    break;
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-18
      • 1970-01-01
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 1970-01-01
      • 2023-04-07
      • 2017-01-01
      • 1970-01-01
      相关资源
      最近更新 更多