目標是寫出這樣的程式碼:
d.wait(3000).run(function(m){ // 等待 3 秒
alert('從前有座山');
}).wait(1000).run(function(m){ // 等待 1 秒
alert('山裡有座廟');
}).wait(2000).run(function(m){ // 等待 2 秒
alert('廟裡有一個老和尚給一個小和尚講故事');
}).wait(3000).run(function(m){ // 等待 3 秒
alert('講的故事是:');
}).goStart(); // 跳到第一條重新執行,這句拿掉就只執行一次
讀起來幾乎就像在寫劇本,這正是鏈式 API 的價值。
<!doctype html>
<html>
<head>
<title>異步執行</title>
</head>
<body>
<script type="text/javascript">
function Delay(){
this.funList= [];
this.index = 0;
this.re = null;
this.isloop = false;
};
Delay.prototype = {
wait:function(m){
if(this.funList[this.index] && typeof this.funList[this.index].fun != 'function'){
m += this.funList[this.index].m;
}
this.funList[this.index] = {m:m,fun:null};
return this;
},
run:function(fun){
if(typeof this.funList[this.index].fun != 'function'){
this.funList[this.index].fun = fun;
this.index++;
}else{
this.index++;
this.funList[this.index] = {'m':0,'fun':fun};
}
this.start();
return this;
},
start:function(){
var self = this;
if(this.re) return;
var setOutrun = function(funList,index){
if(funList[index] == undefined){
clearTimeout(self.re);
return false;
}
var m = funList[index].m,
fun = funList[index].fun;
typeof fun == 'function' || (fun = function(){});
self.re = setTimeout(function(){
if(fun(index) === false)return false;
if(self.isloop){
index = -1;
self.isloop = false;
}
setOutrun(funList,++index);
},m);
}
setOutrun(this.funList,0);
},
stop:function(){
return clearTimeout(this.re);
},
goStart:function(){
var self = this,
fun = function(){
self.isloop = true;
};
if(this.funList[this.index] && typeof this.funList[this.index].fun != 'function'){
this.funList[this.index].fun = fun;
this.index++;
}else{
this.funList[this.index] = {'m':0,'fun':fun};
}
this.start();
}
};
var d = new Delay();
d.wait(3000).run(function(m){
alert('從前有座山');
}).wait(2000).run(function(m){
alert('山裡有座廟');
}).wait(2000).run(function(m){
alert('廟裡有一個老和尚給一個小和尚講故事');
}).wait(2000).run(function(m){
alert('講的故事是:');
}).goStart();
</script></body>
</html>
資料結構:一個任務陣列。 funList 中每個元素是 {m: 延遲毫秒, fun: 回呼}。wait 負責寫入 m,run 負責寫入 fun,兩者共用同一個 index 游標。
wait 的累加邏輯。 如果目前位置已經有物件但 fun 還不是函式(代表連續呼叫了兩次 wait),就把新的 m 累加到舊的上面,而不是覆蓋。這讓 wait(1000).wait(2000) 等於等 3 秒,符合直覺。
start 的重入保護。 if(this.re) return; 這一行很關鍵。因為 run 每次被呼叫都會觸發 start,而鏈式寫法會連續呼叫多次 run;若不加保護,就會同時跑好幾條 setTimeout 鏈,畫面變成亂序跳 alert。
遞迴排程。 setOutrun 是核心:設定一個 timeout,時間到後執行該任務,然後以 index+1 遞迴排下一個。這其實是把「非同步的串行執行」用手寫的 continuation 串起來。
goStart 的循環技巧。 它在佇列末尾插入一個只把 isloop 設為 true 的任務。當排程跑到它時,isloop 被打開,於是下一輪把 index 重置為 -1,整條鏈從頭再跑一次。
這個模式在 Promise 與 async/await 出現之後,可以簡化到幾乎不需要思考:
const sleep = ms => new Promise(r => setTimeout(r, ms));
const tasks = [
[3000, () => alert('從前有座山')],
[1000, () => alert('山裡有座廟')],
[2000, () => alert('廟裡有一個老和尚給一個小和尚講故事')],
[3000, () => alert('講的故事是:')],
];
async function play(loop = false) {
do {
for (const [ms, fn] of tasks) {
await sleep(ms);
fn();
}
} while (loop);
}
play(true);
手寫版本的價值在於:它逼你親自處理「重入保護」、「狀態機」、「串行非同步流程」這些真實問題。等你用 Promise 寫過一遍,就會更清楚 async/await 到底替你解決了什麼。