原創聲明:本文為作者原創,未經允許不得轉載,經授權轉載需注明作者和出處
本文主要有關系的是co模塊
無論是前端還是后端,對于異步回調都很了解熟悉,瀏覽器中的各種交互邏輯都是通過事件回調實現的,前端邏輯越來越復雜,導致回調函數越來越多。
有的時候,由于我們業務的需要,我們必須得使用過多的回調函數嵌套
$.post('/app/user', function(data) {
console.log(data);
$.post('/app/banks',{''userId":"data.userId''}, function(result) {
console.log(result);
$.post('/app/money',{''cardNo":"result.cardNo''}, function(res) {
console.log(res.howMuchMoney)
});
});
});
function co(gen) {
var ctx= gen();
var ret = ctx.next();
ret.value.then(function(res) {
ctx.next(res);
});
}
首先生成一個迭代器,然后執行一遍 next(),得到的 value 是一個 Promise 對象,Promise.then() 里面再執行 next()。當然這只是一個原理性的演示,很多錯誤處理和循環調用 next() 的邏輯都沒有寫出來。
傳統模式:hahahello是一個異步函數
function hahahello() {
return Promise.resolve('hello').then(function(hello) {
console.log(hello);
});
}
function helloworld() {
hahahello();
console.log('world');
}
helloworld();
輸出
"world"
"hello"
co 模塊:
function co(gen) {
var ctx= gen();
var ret = ctx.next();
ret.value.then(function(res) {
ctx.next(res);
});
}
function hahahello() {
return Promise.resolve('hello').then(function(hello) {
console.log(hello);
});
}
co(function *helloworld() {
yield hahahello();
console.log('world');
});
此時輸出
"hello"
"world"
var co = require('co');
co(function *() {
yield sayI();
yield sayLove();
yield sayYou();
yield sayXiaohuangxiang();
});
打印出:
I
Love
You
Xiaohuangxiang
根據meikidd文章學習心得