JavaScript 的一大優勢,就在於它處理非同步程式碼的方式。非同步程式碼會被放進一個事件佇列,等到其他程式碼都執行完畢後才處理,而不會阻斷執行緒。然而對初學者而言,撰寫非同步程式碼往往是一大難題。本文將逐一釐清你可能有的困惑。
JavaScript 最基礎的非同步函式是 setTimeout 與 setInterval。setTimeout 會在指定時間後執行給定的函式,它接受一個回呼函式作為第一個參數、毫秒數作為第二個參數。用法如下:
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 規範都點明了這個問題:
有趣的是,直到同一段程式碼中所有其餘部分都執行完畢後,逾時才會發生。也就是說,如果你設定了逾時,同時又執行了一段耗時的函式,那麼在該函式執行完成之前,逾時甚至不會啟動。事實上,像 setTimeout 與 setInterval 這類非同步函式,會被壓入一個稱為 Event Loop 的佇列。
Event Loop 是一個回呼函式的佇列。當非同步函式執行時,回呼函式會被壓入這個佇列。JavaScript 引擎會等到非同步函式執行完畢後,才開始處理事件循環。這意味著 JavaScript 程式碼並非多執行緒,即使它的行為看起來類似。事件循環是一個先進先出(FIFO)的佇列,代表回呼會依照被加入佇列的順序執行。Node 之所以選用 JavaScript 作為開發語言,正是因為撰寫這類程式碼是多麼簡單。
非同步的 JavaScript 與 XML(AJAX)徹底改變了這門語言的樣貌。突然之間,瀏覽器不再需要重新載入就能更新網頁內容。在不同瀏覽器中實作 Ajax 的程式碼可能冗長又乏味;所幸有 jQuery(還有其他函式庫)的幫忙,我們得以優雅而輕鬆地實現用戶端與伺服器端的通訊。
我們可以用 jQuery 的跨瀏覽器介面 $.ajax 輕易取得資料,卻看不到背後究竟發生了什麼。例如:
var data; $.ajax({ url: "some/url/1", success: function( data ) { // But, this will! console.log( data ); } }) // Oops, this won't work... console.log( data ); 常見的錯誤是在呼叫 $.ajax 之後馬上使用 data,但實際上底層是這樣運作的:
xmlhttp.open( "GET", "some/ur/1", true ); xmlhttp.onreadystatechange = function( data ) { if ( xmlhttp.readyState === 4 ) { console.log( data ); } }; xmlhttp.send( null ); 底層的 XmlHttpRequest 物件發起請求、設定回呼來處理 XHR 的 readystatechange 事件,然後執行 XHR 的 send 方法。在 XHR 運作期間,每當 readyState 屬性改變時 readystatechange 事件就會觸發,唯有在 XHR 從遠端伺服器接收完畢響應後,回呼函式才會真正執行。
非同步程式設計很容易陷入所謂的「回呼地獄」。因為幾乎所有 JavaScript 的非同步函式都用到了回呼,連續執行幾個非同步函式,結果就是層層嵌套的回呼以及隨之而來的複雜程式碼。
Node.js 中的許多函式也是非同步的,因此如下的程式碼相當常見:
var fs = require( "fs" ); fs.exists( "index.js", function() { fs.readFile( "index.js", "utf8", function( err, contents ) { contents = someFunction( contents ); // do something with 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({ origin: [ fromLatLng.lat(), fromLatLng.lng() ], destination: [ toLatLng.lat(), toLatLng.lng() ], travelMode: "driving", unitSystem: "imperial", callback: function( e ){ console.log( "ANNNND FINALLY here's the directions..." ); // do something with e } }); } } }); } } }); 巢狀回呼很容易帶來程式碼裡的「壞味道」,不過你可以嘗試以下幾種風格來解決這個問題。一句話總結:沒有糟糕的語言,只有糟糕的程式設計師。
清除巢狀回呼的一個便捷做法,就是避免超過兩層的嵌套。與其傳入匿名函式,不如傳入一個具名的函式作為回呼:
var fromLatLng, toLatLng; var routeDone = function( e ){ console.log( "ANNNND FINALLY here's the directions..." ); // do something with e }; 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 函式庫也能幫我們處理多重 Ajax 請求與響應,例如:
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] ); }); 這段程式碼執行兩個非同步函式,每個函式都接收一個名為「done」的回呼,並在結束時呼叫它。當兩個 done 回呼都完成後,parallel 的回呼便會被呼叫,用以處理這兩個非同步函式產生的結果或錯誤。
依據 CommonJS/A 的定義,promise 代表一項操作獨立完成後回傳的最終結果。
許多函式庫都內含 promise 模型,其中 jQuery 就提供了一套實用而出色的 promise API。jQuery 在 1.5 版引入了 Deferred 物件,並可在回傳 promise 的函式中使用 jQuery.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(); }; var doSomethingCoolWithDirections = function( route ) { // do something with route }; $.when( geocode( fromAddress ), geocode( toAddress ) ). then(function( fromLatLng, toLatLng ) { getRoute( fromLatLng, toLatLng ).then( doSomethingCoolWithDirections ); }); 這樣一來,你就能先執行兩個非同步函式、等待它們的結果,再用先前兩次呼叫的結果去執行另一個函式。在這段程式碼中,geocode 方法被呼叫兩次並各自回傳一個 promise;非同步函式執行後,在其回呼裡呼叫 resolve;一旦兩次 resolve 都完成,then 便會執行,接收先前兩次 geocode 的回傳結果,接著傳入 getRoute(它同樣回傳 promise),最後當 getRoute 的 promise 解決後,doSomethingCoolWithDirections 回呼就執行了。
事件是另一種處理非同步回呼完成後的通訊方式。一個物件可以成為事件發射器並派發事件,另一個物件則監聽這些事件。這類事件處理方式被稱為觀察者模式。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 ) { // do something with data } }); var view = new SomeView({ model: new SomeModel() }); 還有其他用於發射事件的混合函式庫,例如 jQuery Event Emitter、EventEmitter、monologue.js,以及 Node.js 內建的 EventEmitter 模組。
還有一種類似的派發訊息方式稱為中介者模式,postal.js 採用的正是這種做法。在中介者模式中,有一個供所有物件監聽與派發事件的「中間人」。這樣一來,物件之間不再直接互相依賴,从而实现了解耦。
切記不要向公用 API 回傳 promise。這不僅關係到 API 使用者對 promise 的使用,也會讓重構變得更困難。不過,把內部用途的 promise 與對外介面的事件結合起來,卻能讓應用變得更低耦合、更易測試。
在先前的範例中,doSomethingCoolWithDirections 回呼在兩個 geocode 函式完成後執行,接著它會取得 getRoute 回傳的響應,並將其作為訊息發送出去:
var doSomethingCoolWithDirections = function( route ) { postal.channel( "ui" ).publish( "directions.done", { route: route }); }; 這樣一來,應用的其他部分就不必直接參照發出請求的物件,也能響應非同步回呼。當取得指令時,頁面上很可能有多個區域都需要更新。在典型的 jQuery Ajax 流程中,回呼往往得為此做相應調整,這會讓程式碼難以維護;但透過訊息機制,處理多個 UI 區域的更新就單純多了。
var UI = function() { this.channel = postal.channel( "ui" ); this.channel.subscribe( "directions.done", this.updateDirections ).withContext( this ); }; UI.prototype.updateDirections = function( data ) { // The route is available on data.route, now just update the UI }; app.ui = new UI(); 另外還有 amplify、PubSubJS 與 radio.js 等基於中介者模式傳送訊息的函式庫。
JavaScript 讓撰寫非同步程式碼變得很容易。善用 promises、事件或命名函式,就能避免陷入「回呼地獄」。若想深入了解 JavaScript 非同步程式設計,可以參考 Async JavaScript: Build More Responsive Apps with Less,更多範例託管在 GitHub 的 NetTutsAsyncJS 專案上,不妨馬上 clone 下來動手試試!