JavaScript 的強項之一,就是它處理非同步程式碼的方式。非同步工作會被放進一個佇列,等目前所有程式碼執行完才處理,因此不會阻塞執行緒。但對初學者而言,寫非同步程式碼往往是挫折的來源。本文試著把這件事講清楚。
最基礎的非同步函式是 setTimeout 與 setInterval。前者接受一個回呼函式與毫秒數:
console.log("a");
setTimeout(function () { console.log("c"); }, 500);
setTimeout(function () { console.log("d"); }, 500);
setTimeout(function () { console.log("e"); }, 500);
console.log("b");
輸出順序是 a、b,約 500 毫秒後才是 c、d、e。我說「約」是因為 setTimeout 並不精確,HTML5 規範自己就寫明了:由於 CPU 負載與其他任務造成的延遲是可以預期的。
更值得注意的一點是:計時器要等目前這段程式碼全部執行完才會啟動。如果你設了 0 毫秒的 timeout,然後跑一個耗時 5 秒的迴圈,那個 timeout 會在 5 秒後才觸發。
原因就在事件循環(Event Loop)。這是一個回呼函式的佇列,先進先出。非同步函式執行時,回呼被壓入佇列;JavaScript 引擎要等到目前所有程式碼跑完,才開始處理這個佇列。所以 JavaScript 並不是多執行緒的——它只是看起來像。Node.js 之所以適合寫這種程式,正是因為這個模型單純。
Ajax 永久改變了 JavaScript 的處境:瀏覽器不再需要重新載入就能更新頁面。跨瀏覽器的實作原本冗長乏味,jQuery 等庫把它優雅化了。
但方便也掩蓋了真相。這樣寫會出錯:
var data;
$.ajax({
url: "some/url/1",
success: function (data) {
console.log(data); // 這裡有值
}
});
console.log(data); // 這裡是 undefined
揭開 jQuery 的包裝,底層是這樣:
xmlhttp.open("GET", "some/url/1", true);
xmlhttp.onreadystatechange = function (data) {
if (xmlhttp.readyState === 4) {
console.log(data);
}
};
xmlhttp.send(null);
請求被送出後程式碼繼續往下跑,直到 readyState 變成 4(完成)時,回呼才被觸發。這就是為什麼 $.ajax 之後那一行拿不到資料——它執行在回呼之前。
Node.js 的函式大多是非同步的,於是這種結構變得無所不在:
var fs = require("fs");
fs.exists("index.js", function () {
fs.readFile("index.js", "utf8", function (err, contents) {
contents = someFunction(contents);
fs.writeFile("index.js", "utf8", function () {
console.log("whew! Done finally...");
});
});
});
console.log("executing...");
客戶端也有同樣的問題,例如連續的地理編碼呼叫:
GMaps.geocode({ address: fromAddress, callback: function (results, status) {
if (status == "OK") {
fromLatLng = results[0].geometry.location;
GMaps.geocode({ address: toAddress, callback: function (results, status) {
if (status == "OK") {
toLatLng = results[0].geometry.location;
map.getRoutes({ /* ... */ callback: function (e) {
console.log("ANNNND FINALLY here's the directions...");
}});
}
}});
}
}});
問題不在語言本身,而在使用方式。
最簡單的做法是避免超過兩層的巢狀,把回呼改成具名函式:
var fromLatLng, toLatLng;
var routeDone = function (e) {
console.log("ANNNND FINALLY here's the directions...");
};
var toAddressDone = function (results, status) {
if (status == "OK") {
toLatLng = results[0].geometry.location;
map.getRoutes({
origin: [fromLatLng.lat(), fromLatLng.lng()],
destination: [toLatLng.lat(), toLatLng.lng()],
travelMode: "driving",
unitSystem: "imperial",
callback: routeDone
});
}
};
var fromAddressDone = function (results, status) {
if (status == "OK") {
fromLatLng = results[0].geometry.location;
GMaps.geocode({ address: toAddress, callback: toAddressDone });
}
};
GMaps.geocode({ address: fromAddress, callback: fromAddressDone });
async.js 則能處理並行的多重請求:
async.parallel([
function (done) {
GMaps.geocode({ address: toAddress, callback: function (result) {
done(null, result);
}});
},
function (done) {
GMaps.geocode({ address: fromAddress, callback: function (result) {
done(null, result);
}});
}
], function (errors, results) {
getRoute(results[0], results[1]);
});
CommonJS/A 的定義是:promise 代表一個操作完成後的最終結果。
jQuery 自 1.5 起提供 Deferred 物件。把非同步操作包成回傳 promise 的函式:
var geocode = function (address) {
var dfd = new $.Deferred();
GMaps.geocode({ address: address, callback: function (response, status) {
return dfd.resolve(response);
}});
return dfd.promise();
};
var getRoute = function (fromLatLng, toLatLng) {
var dfd = new $.Deferred();
map.getRoutes({
origin: [fromLatLng.lat(), fromLatLng.lng()],
destination: [toLatLng.lat(), toLatLng.lng()],
travelMode: "driving",
unitSystem: "imperial",
callback: function (e) { return dfd.resolve(e); }
});
return dfd.promise();
};
$.when(geocode(fromAddress), geocode(toAddress))
.then(function (fromLatLng, toLatLng) {
getRoute(fromLatLng, toLatLng).then(doSomethingCoolWithDirections);
});
巢狀消失了,變成一條線性的鏈:兩個 geocode 並行,都完成後才呼叫 getRoute,再串上最後的處理。
事件是另一種通知機制:一個物件發射事件,另一個物件監聽。這稱為觀察者模式,Backbone.js 的 Backbone.Events 就是這樣的模組:
var SomeModel = Backbone.Model.extend({ url: "/someurl" });
var SomeView = Backbone.View.extend({
initialize: function () {
this.model.on("reset", this.render, this);
this.model.fetch();
},
render: function (data) {
// 處理資料
}
});
var view = new SomeView({ model: new SomeModel() });
jQuery Event Emitter、EventEmitter、monologue.js 以及 Node 內建的 events 模組都屬於這類。
另一種相關但不同的做法是中介者模式,postal.js 採的就是這條路。差別在於:所有物件都透過一個中間人來監聽與派發,彼此不產生直接關聯,因此完全分離。
實務上的一個建議:不要在公開 API 上回傳 promise。這會讓 API 使用者被綁進 promise 的實作細節,也讓重構變困難。比較好的組合是內部用 promise、對外用事件:
var doSomethingCoolWithDirections = function (route) {
postal.channel("ui").publish("directions.done", { route: route });
};
訂閱端:
var UI = function () {
this.channel = postal.channel("ui");
this.channel.subscribe("directions.done", this.updateDirections).withContext(this);
};
UI.prototype.updateDirections = function (data) {
// data.route 可用,更新畫面即可
};
app.ui = new UI();
這樣做的好處在於:應用程式的其他部分不必持有發出請求的物件的參照,就能響應非同步結果。在典型的 jQuery Ajax 流程中,一次回呼往往得同時更新頁面上好幾個區域,回呼函式會越寫越腫。改用訊息之後,每個區域各自訂閱自己關心的部分,維護成本立刻下降。其他可考慮的中介者函式庫還有 amplify、PubSubJS 與 radio.js。
JavaScript 讓寫非同步程式碼變得容易,也容易寫錯。實務上有四個方向可以避開回呼地獄:具名函式降低巢狀深度、async.js 處理流程協調、promise(今日的首選是原生 Promise 與 async/await)讓非同步寫得像同步、事件與訊息切開元件之間的耦合。
而所有這些技巧的共同前提,是真正理解事件循環那條佇列的存在——知道你的程式碼什麼時候執行、什麼時候只是被排進隊列,其餘的判斷才有依據。