One of the strengths of JavaScript is how it handles asynchronous code. Asynchronous code is put into an event queue and waits until all other code is executed without blocking the thread. However, writing asynchronous code can be difficult for beginners. And in this article, I will clear up any confusion you may have.
Understanding asynchronous code
The most basic asynchronous functions in JavaScript are setTimeout and setInterval. setTimeout will execute the given function after a certain period of time. It accepts a callback function as the first parameter and a millisecond time as the second parameter. The following are usage examples:
console.log( "a" ); setTimeout(function() { console.log( "c" ) }, 500 ); setTimeout(function() { console.log( "d" ) }, 500 ); setTimeout(function() { console.log( "e" ) }, 500 ); console.log( "b" );
As expected, the console first outputs "a" and "b", and about 500 milliseconds later, "c", "d", and "e" are seen. I use "approximately" because setTimeout is actually unpredictable. In fact, even the HTML5 specification mentions this issue:
Interestingly, the timeout does not occur until all remaining code in the same segment has finished executing. So if a timeout is set and a long-running function is executed, the timeout won't even start until the function completes. In fact, asynchronous functions, such as setTimeout and setInterval, are pushed into a queue called Event Loop.
Event Loop is a callback function queue. When the asynchronous function is executed, the callback function will be pushed into this queue. The JavaScript engine will not start processing the event loop until the asynchronous function execution is completed. This means that the JavaScript code is not multi-threaded, even though it behaves similarly. The event loop is a first-in-first-out (FIFO) queue, which means callbacks are executed in the order in which they are enqueued. JavaScript was chosen as the development language for Node because of how easy it is to write such code.
Ajax
Asynchronous Javascript and XML (AJAX) have permanently changed the landscape of the Javascript language. Suddenly, the browser no longer needs to reload to update web pages. The code to implement Ajax in different browsers can be long and tedious; however, thanks to the help of jQuery (and other libraries), we can achieve client-server communication in an easy and elegant way.
We can easily retrieve data using the jQuery cross-browser interface $.ajax, however we cannot show what is happening behind the scenes. For example:
var data; $.ajax({ url: "some/url/1", success: function( data ) { // But, this will! console.log( data ); } }) // Oops, this won't work... console.log( data );
The most common mistake is to use data immediately after calling $.ajax, but in fact it is like this:
xmlhttp.open( "GET", "some/ur/1", true ); xmlhttp.onreadystatechange = function( data ) { if ( xmlhttp.readyState === 4 ) { console.log( data ); } }; xmlhttp.send( null );
The underlying XmlHttpRequest object initiates a request and sets a callback function to handle the readystatechnage event of XHR. Then execute the send method of XHR. When XHR is running, the readystatechange event will be triggered when its attribute readyState changes, and the callback function will trigger execution only when XHR ends receiving a response from the remote server.
Handling asynchronous code
Asynchronous programming can easily fall into what we often call "callback hell". Because in fact almost all asynchronous functions in JS use callbacks, the result of continuously executing several asynchronous functions is layers of nested callback functions and the resulting complex code.
Many functions in node.js are also asynchronous. Therefore the following code is basically very common:
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..." );
The following client code is also common:
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 } }); } } }); } } });
Nested callbacks can get really nasty, but there are several solutions to this style of coding.
Nested callbacks can easily bring "bad smell" in the code, but you can use the following styles to try to solve this problem
There are no bad languages, only bad programmers - Asynchronous JavaScript
Named function
A convenient solution for clearing nested callbacks is to simply avoid more than two levels of nesting. Pass a named function as the callback parameter instead of passing an anonymous function:
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 });
In addition, the async.js library can help us handle multiple Ajax requests/responses. For example:
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函数的回调函数被调用并执行或处理这两个异步函数产生的结果或错误。
Promises模型
引自 CommonJS/A:
有很多库都包含了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 库在withBackbone.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 库中用的即是这种方式。在中介者模式,有一个用于所有对象监听和派发事件的中间人。在这种模式下,一个对象不与另外的对象产生直接联系,从而使得对象间都互相分离。
绝不要返回promise到一个公用的API。这不仅关系到了API用户对promises的使用,也使得重构更加困难。不过,内部用途的promises和外部接口的事件的结合,却可以让应用更低耦合且便于测试。
在先前的例子里面,doSomethingCoolWithDirections回调函数在两个geocode函数完成后执行。然后,doSomethingCoolWithDirections才会获得从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, and radio.js。
结论
JavaScript 使得编写异步代码很容易. 使用 promises, 事件, 或者命名函数来避免“callback hell”. 为获取更多javascript异步编程信息,请点击Async JavaScript: Build More Responsive Apps with Less . 更多的实例托管在github上,地址NetTutsAsyncJS,赶快Clone吧 !