1秩霍、回調(diào)函數(shù)
function f1(callback) {
// f1 的代碼
// f1 執(zhí)行完成后帮掉,調(diào)用回調(diào)函數(shù)
callback();
}
類(lèi)同于
f1(f2);
2壮锻、采用時(shí)間驅(qū)動(dòng)模式,事件監(jiān)聽(tīng)
function f1(){
setTimeout(function () {
// f1的任務(wù)代碼
f1.trigger('done');
}, 1000);
}
function f2(){
console.log('事件監(jiān)聽(tīng)');
}
f1.on('done',f2);
3倍靡、發(fā)布訂閱,類(lèi)同于rabbitmq生產(chǎn)者课舍,消費(fèi)者機(jī)制
function f1(){
setTimeout(function () {
// f1的任務(wù)代碼
jQuery.publish("done");
}, 1000);
}
jQuery.subscribe("done", f2);
異步流程控制
async(1, function(value){
async(value, function(value){
async(value, function(value){
async(value, function(value){
async(value, function(value){
async(value, final);
});
});
});
});
});
```
串行執(zhí)行
```javascript
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
function series(item) {
if(item) {
async( item, function(result) {
results.push(result);
return series(items.shift());
});
} else {
return final(results);
}
}
series(items.shift());
```
并行執(zhí)行
```javascript
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
items.forEach(function(item) {
async(item, function(result){
results.push(result);
if(results.length == items.length) {
final(results);
}
})
});
```
并行與串行的結(jié)合
```javascript
var items = [ 1, 2, 3, 4, 5, 6 ];
var results = [];
var running = 0;
var limit = 2;
function launcher() {
while(running < limit && items.length > 0) {
var item = items.shift();
async(item, function(result) {
results.push(result);
running--;
if(items.length > 0) {
launcher();
} else if(running == 0) {
final(results);
}
});
running++;
}
}
launcher();
```
promise
```javascript
(new Promise(f1)).then(f2);
```
```javascript
// 傳統(tǒng)寫(xiě)法
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// ...
});
});
});
});
// Promises的寫(xiě)法
(new Promise(step1))
.then(step2)
.then(step3)
.then(step4);
```
Promise對(duì)象的優(yōu)點(diǎn)在于塌西,讓回調(diào)函數(shù)變成了規(guī)范的鏈?zhǔn)綄?xiě)法