我可以用什么来替换嵌套的异步回调?

Tho*_*ggi 4 javascript asynchronous middleware callback node.js

可以说我想发送一封电子邮件然后更新数据库,这两个动作都是异步的.这就是我通常写它的方式.

send_email(function(err, id){
    if(err){
        console.log("error");
    }else{
        update_database(id,function(err, id){
            if(err){
                console.log("error");
            }else{
                console.log("success");
            }
        });
    }
});
Run Code Online (Sandbox Code Playgroud)

我想用中间件来做这件事.

var mid = {};

mid.send_email = function(){
    return function(next){
        send_email(function(err,id){
            if(err){
                console.log("error");
            }else{
                next(id);
            }
        });
    }
}

mid.update_database = function(){
    return function(id,next){
        update_database(id,function(err,id){
            if(err){
                console.log("error");
            }else{
                next(id);
            }
        });
    }
}

mid.success = function(){
    return function(id,next){
        console.log("success")
        next(id);
    }   
}
Run Code Online (Sandbox Code Playgroud)

堆叠中间件.

middleware.use(mid.send_email());
middleware.use(mid.update_database());
middleware.use(mid.success());
Run Code Online (Sandbox Code Playgroud)

手头有两个主要问题.

  • 如何使用中间件代替嵌套回调?
  • 是否可以将变量传递给next()

Jea*_*ond 5

你想要的是能够处理异步控制流程.很多js库可以帮助您实现这一目标.您可以尝试Async使用该waterfall函数的库,因为您希望能够将变量传递给将要执行的下一个函数:

https://github.com/caolan/async#waterfall

"运行一系列函数,每个函数都将它们的结果传递给数组中的下一个.但是,如果任何函数将错误传递给回调,则不执行下一个函数,并立即调用主回调并返回错误".

示例:

async.waterfall([
    function(callback){
        callback(null, 'one', 'two');
    },
    function(arg1, arg2, callback){
        callback(null, 'three');
    },
    function(arg1, callback){
        // arg1 now equals 'three'
        callback(null, 'done');
    }
], function (err, result) {
   // result now equals 'done'    
});
Run Code Online (Sandbox Code Playgroud)