回调之痛

204 阅读3分钟

本人接触Node.js比较早,早期0.x.x版本Node.js不支持Promise,所以基本上都是回调!

都知道Node.js的优点是 "高并发 I/O密集" ,因为Node.js的I/O请求都是异步的(如:sql查询请求、文件流操作操作请求、http请求...)

痛点

如:单条的异步回调请求:

api(query, function(err, val1){
    //do something 
});

单次请求还好,如果回调之间产生依赖关系代码就会写成这个样子:

step1(function (value1) {
    step2(value1, function(value2) {
        step3(value2, function(value3) {
            step4(value3, function(value4) {
                // Do something with value4
            });
        });
    });
});

这里只有4个,那如果更多呢?会不会崩溃,反正我会!有解决办法么? 答案是就是:promise/a+规范,下面我们看一下promise/a+规范

链式调用

先举个jQuery的链式写法例子:

$('#tab').eq($(this).index()).show().siblings().hide();

链式写法的核心是:每个方法都返回this(自己看jquery源码)

下面举一个this的简单例子:

var obj = {
  step1:function(){
    console.log('a');
    return this;
  },
  step2:function(){
    console.log('b');    
    return this;
  },
  step3:function(){
    console.log('c');
    return this;
  },
  step4:function(){
    console.log('d');
    return this;
  }
}

console.log('-----\n');
obj.step1().step2().step3();
console.log('-----\n');
obj.step4().step2().step1();

执行结果:

$ node doc/this.js
-----

a
b
c
-----

c
b
a

为啥要讲这个呢?先回到异步调用的场景,我们能这样调用么?如果每一个操作都可以连起来,是不是很爽?比如:

return step1().step2().step3().step4()

这样做的好处

  • 每一个操作都是独立的函数
  • 可组装,拼就好了

但是这还不够?

我还需要:

  1. 下一步获得上一步的输出结果
  2. 出错能捕获异常
  3. 在函数里处理业务流程

可以吗?答案是 : node-seqasync

因为很久很久很久以前用的是[node-seq](https://github.com/substack/node-seq),所以这里已[node-seq](https://github.com/substack/node-seq)为例。 [node-seq](https://github.com/substack/node-seq) 已经6+年没有维护了,而且`.par`方法有Bug,**不再建议使用**!!! 建议使用:[async](https://github.com/caolan/async)

串行:

....
new Seq()
	.seq(function(){
        tf_api({tid : 123}, this);
	})
	.seq(function(task){
        customer_api({cuid : task.cuid}, this);
	})
	.seq(function(customer){
	    var that = this;
	    
	    fin_api(customer, function(err, result){
	        if(err) that(err);
	        
	        cb(null, result);
	    });
	})
	.catch(function(err){
        cb(err);
	});
....

并行:

new Seq()
	.par('task', function(){
        tf_api({tid : 123}, this);
	})
	.par('customer', function(){
        customer_api({cuid : 456}, this);
	})
	.seq(function(){
	    var that = this,
	        task = this.vars.task,
	        customer = this.vars.customer;
	        
        driver_api({did : 789}, function(err, ret){
            if(err) return that(err);
            
            return cb(null, {...});
        });
	})
	.catch(function(err){
        cb(err);
	});

还有没其他的?当然~~~ 他就是:** promise/a+规范**

Promise

//刚才的链式操作
action.a().b().c().d();
//Promise的链式操作
action().then(a).then(b).then(c)

Promise是把函数传入他的then方法 如果失败呢?

action().then(a).then(b).then(c).catch(function(err){
    //do something
});

Promise/A+

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Promise = require("bluebird");
UserSchema = new Schema({
  username: String,
  password: String,
  created_at: {
    type: Date,
    "default": Date.now
  }
});
var User = mongoose.model('User', UserSchema);
Promise.promisifyAll(User);
Promise.promisifyAll(User.prototype);

查询:

User.findAsync({username: username}).then(function(data) {
   ...
}).catch(function(err) {
   ...
});

还有没更爽的呢? ES6上的Generators/yield

function* gen () {  
    yield 'hello';
    yield 'world';
}
var g =  gen(); // 返回的其实是一个迭代器
console.log(g.next());    // { value: 0, done: false }  
console.log(g.next());    // { value: 1, done: false }  
console.log(g.next());    // { value: undefined, done: true }

co + Promise

co 是著名的tj大神写的,是一个为Node.js和浏览器打造的基于生成器的流程控制工具,借助于Promise,你可以使用更加优雅的方式编写非阻塞代码。

co(function *(){
	var task = yield tf_api(query);
	//or
	var customer = customer_api(task.cuid);
	var drivers = driver_api(task.bids);
	var citys = citys_api(task.citys);
	var bid_mgr = admin_user_api(task.bid_mgr_id);
	var warehouse  = warehouse_api(task.wid);
	
	return yield [
			customer,
			drivers,
			citys,
			bid_mgr,
			warehouse
	    ];
	}).then(function(info){
	   //....do something
	}).catch(function(err){
		console.log(err);
	});

是不是非常爽

Async/await

在ES7(还未正式标准化)中引入了Async函数的概念,详细信息去Node.js技术栈之Promise阅读

最后补上一张图:

file

参考资料:

Promise/A+规范 Node.js技术栈之Promise 一起来实现co 简单实现Promise/A+ Generator 函数的含义与用法