在es6中引入的原生Promise为js的异步回调问题带来了一个新的解决方式,而TJ大神写的co模块搭配Generator函数的同步写法,更是将js的异步回调带了更优雅的写法。
今天我想对比一下这两种方式,来看看这两种方式的区别以及优劣。
我们先抽象几个操作:
以做饭为例,我们先去买菜,回来洗菜,刷碗,烧菜,最后才是吃。定义如下方法:
var buy = function (){}; //买菜,需要3svar clean = function(){}; //洗菜,需要1svar wash = function(){}; //刷碗,需要1svar cook = function(){}; //煮菜,需要3svar eat = function () {}; //吃饭,2s,最后的一个步骤。
在实际中,我们可能这样,先去买菜,然后洗菜,然后开始烧菜,烧菜的同时,刷碗,等碗刷完了,菜煮好了,我们才开始吃饭。也就是,煮菜和刷碗是并行的。
Promise方式
var begin = new Date();buySomething().then((buyed)=>{ console.log(buyed); console.log(new Date()-begin); return clean();}).then((cleaned)=>{ console.log(cleaned); console.log(new Date()-begin); return Promise.all([cook(),wash()]);}).then((value)=>{ console.log(value); console.log(new Date()-begin); return eat();}).then((eated)=>{ console.log(eated); console.log(new Date()-begin);}).catch((err)=>{ console.log(err);});
输出结果:
菜买到啦
3021
菜洗乾 了
4023
[ ' 菜煮好了,可以吃 了', ' 子洗乾 啦' ]
7031