在es6中引入的原生Promise為js的異步回調(diào)問題帶來了一個新的解決方式,而TJ大神寫的co模塊搭配Generator函數(shù)的同步寫法,更是將js的異步回調(diào)帶了更優(yōu)雅的寫法。
今天我想對比一下這兩種方式,來看看這兩種方式的區(qū)別以及優(yōu)劣。
我們先抽象幾個操作:
以做飯為例,我們先去買菜,回來洗菜,刷碗,燒菜,最后才是吃。定義如下方法:
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
飯吃完了,好舒服啊
9034
Promise里有個all()方法,可以傳遞一個promise數(shù)組,功能是當所有promise都成功時,才返回成功。上面的例子,我們就將 cook()和wash()放到all()方法,模擬兩個操作同時進行。從時間上來看,先去買菜,耗時3s,洗菜耗時1s,輸出4023,刷碗和煮菜同時進行,以耗時長的煮菜3s,輸出7031,最后吃飯2s,輸出9034。
Promise的優(yōu)勢就是,可以隨意定制Promise鏈,去掌控你的流程,想要同步的時候,就使用Promise鏈,想要異步,就使用Promise.all(),接口也很簡單,邏輯也很簡單。
co+Generator搭配使用
let begin = new Date();co(function* (){  let buyed = yield buySomething();  console.log(buyed);  console.log(new Date() - begin);  let cleaned = yield clean();  console.log(cleaned);  console.log(new Date() - begin);  let cook_and_wash = yield [cook(),wash()];  console.log(cook_and_wash);  console.log(new Date() - begin);  let eated = yield eat();  console.log(eated);  console.log(new Date() - begin);});輸出:
菜買到啦
3023
菜洗乾淨了
4026
[ '飯菜煮好了,可以吃飯了', '盤子洗乾淨啦' ]
7033
飯吃完了,好舒服啊
新聞熱點
疑難解答
圖片精選