JavaScript - 基于事件的 JavaScript 编程:异步与同步(转)
转载:http://www.oschina.net/translate/event-based-programming-what-async-has-over-sync
JavaScript的优势之一是其如何处理异步代码。异步代码会被放入一个事件队列,等到所有其他代码执行后才进行,而不会阻塞线程。然而,对于初学者来说,书写异步代码可能会比较困难。而在这篇文章里,我将会消除你可能会有的任何困惑。
理解异步代码
JavaScript最基础的异步函数是setTimeout和setInterval。setTimeout会在一定时间后执行给定的函数。它接受一个回调函数作为第一参数和一个毫秒时间作为第二参数。以下是用法举例:
1 console.log( "a" ); 2 setTimeout(function() { 3 console.log( "c" ) 4 }, 500 ); 5 setTimeout(function() { 6 console.log( "d" ) 7 }, 500 ); 8 setTimeout(function() { 9 console.log( "e" ) 10 }, 500 ); 11 console.log( "b" );
正如预期,控制台先输出“a”、“b”,大约500毫秒后,再看到“c”、“d”、“e”。我用“大约”是因为setTimeout事实上是不可预知的。实际上,甚至 HTML5规范都提到了这个问题:
“这个API不能保证计时会如期准确地运行。由于CPU负载、其他任务等所导致的延迟是可以预料到的。”
有趣的是,直到在同一程序段中所有其余的代码执行结束后,超时才会发生。所以如果设置了超时,同时执行了需长时间运行的函数,那么在该函数执行完成之前,超时甚至都不会启动。实际上,异步函数,如setTimeout和setInterval,被压入了称之为Event Loop的队列。
Event Loop是一个回调函数队列。当异步函数执行时,回调函数会被压入这个队列。JavaScript引擎直到异步函数执行完成后,才会开始处理事件循环。这意味着JavaScript代码不是多线程的,即使表现的行为相似。事件循环是一个先进先出(FIFO)队列,这说明回调是按照它们被加入队列的顺序执行的。JavaScript被
node选做为开发语言,就是因为写这样的代码多么简单啊。
Ajax
异步Javascript与XML(AJAX)永久性的改变了Javascript语言的状况。突然间,浏览器不再需要重新加载即可更新web页面。 在不同的浏览器中实现Ajax的代码可能漫长并且乏味;但是,幸亏有jQuery(还有其他库)的帮助,我们能够以很容易并且优雅的方式实现客户端-服务器端通讯。
我们可以使用jQuery跨浏览器接口$.ajax很容易地检索数据,然而却不能呈现幕后发生了什么。比如:
1 var data; 2 $.ajax({ 3 url: "some/url/1", 4 success: function( data ) { 5 // But, this will! 6 console.log( data ); 7 } 8 }) 9 // Oops, this won't work... 10 console.log( data );
较容易犯的错误,是在调用$.ajax之后马上使用data,但是实际上是这样的:
1 xmlhttp.open( "GET", "some/ur/1", true ); 2 xmlhttp.onreadystatechange = function( data ) { 3 if ( xmlhttp.readyState === 4 ) { 4 console.log( data ); 5 } 6 }; 7 xmlhttp.send( null );
底层的XmlHttpRequest对象发起请求,设置回调函数用来处理XHR的readystatechnage事件。然后执行XHR的send方法。在XHR运行中,当其属性readyState改变时readystatechange事件就会被触发,只有在XHR从远端服务器接收响应结束时回调函数才会触发执行。
处理异步代码
异步编程很容易陷入我们常说的“回调地狱”。因为事实上几乎JS中的所有异步函数都用到了回调,连续执行几个异步函数的结果就是层层嵌套的回调函数以及随之而来的复杂代码。
node.js中的许多函数也是异步的。因此如下的代码基本上很常见:
1 var fs = require( "fs" ); 2 fs.exists( "index.js", function() { 3 fs.readFile( "index.js", "utf8", function( err, contents ) { 4 contents = someFunction( contents ); // do something with contents 5 fs.writeFile( "index.js", "utf8", function() { 6 console.log( "whew! Done finally..." ); 7 }); 8 }); 9 }); 10 console.log( "executing..." );
下面的客户端代码也很多见:
1 GMaps.geocode({ 2 address: fromAddress, 3 callback: function( results, status ) { 4 if ( status == "OK" ) { 5 fromLatLng = results[0].geometry.location; 6 GMaps.geocode({ 7 address: toAddress, 8 callback: function( results, status ) { 9 if ( status == "OK" ) { 10 toLatLng = results[0].geometry.location; 11 map.getRoutes({ 12 origin: [ fromLatLng.lat(), fromLatLng.lng() ], 13 destination: [ toLatLng.lat(), toLatLng.lng() ], 14 travelMode: "driving", 15 unitSystem: "imperial", 16 callback: function( e ){ 17 console.log( "ANNNND FINALLY here's the directions..." ); 18 // do something with e 19 } 20 }); 21 } 22 } 23 }); 24 } 25 } 26 });
Nested callbacks can get really nasty, but there are several solutions to this style of coding.
嵌套的回调很容易带来代码中的“坏味道”,不过你可以用以下的几种风格来尝试解决这个问题
The problem isn’t with the language itself; it’s with the way programmers use the language — Async Javascript.
没有糟糕的语言,只有糟糕的程序猿 ——异步JavaSript
命名函数
清除嵌套回调的一个便捷的解决方案是简单的避免双层以上的嵌套。传递一个命名函数给作为回调参数,而不是传递匿名函数:
1 var fromLatLng, toLatLng; 2 var routeDone = function( e ){ 3 console.log( "ANNNND FINALLY here's the directions..." ); 4 // do something with e 5 }; 6 var toAddressDone = function( results, status ) { 7 if ( status == "OK" ) { 8 toLatLng = results[0].geometry.location; 9 map.getRoutes({ 10 origin: [ fromLatLng.lat(), fromLatLng.lng() ], 11 destination: [ toLatLng.lat(), toLatLng.lng() ], 12 travelMode: "driving", 13 unitSystem: "imperial", 14 callback: routeDone 15 }); 16 } 17 }; 18 var fromAddressDone = function( results, status ) { 19 if ( status == "OK" ) { 20 fromLatLng = results[0].geometry.location; 21 GMaps.geocode({ 22 address: toAddress, 23 callback: toAddressDone 24 }); 25 } 26 }; 27 GMaps.geocode({ 28 address: fromAddress, 29 callback: fromAddressDone 30 });
此外, async.js 库可以帮助我们处理多重Ajax requests/responses. 例如:
1 async.parallel([ 2 function( done ) { 3 GMaps.geocode({ 4 address: toAddress, 5 callback: function( result ) { 6 done( null, result ); 7 } 8 }); 9 }, 10 function( done ) { 11 GMaps.geocode({ 12 address: fromAddress, 13 callback: function( result ) { 14 done( null, result ); 15 } 16 }); 17 } 18 ], function( errors, results ) { 19 getRoute( results[0], results[1] ); 20 });
这段代码执行两个异步函数,每个函数都接收一个名为"done"的回调函数并在函数结束的时候调用它。当两个"done"回调函数结束后,parallel函数的回调函数被调用并执行或处理这两个异步函数产生的结果或错误。
Promises模型
引自 CommonJS/A:
promise表示一个操作独立完成后返回的最终结果。
有很多库都包含了promise模型,其中jQuery已经有了一个可使用且很出色的promise API。jQuery在1.5版本引入了Deferred对象,并可以在返回promise的函数中使用jQuery.Deferred的构造结果。而返回promise的函数则用于执行某种异步操作并解决完成后的延迟。
1 var geocode = function( address ) { 2 var dfd = new $.Deferred(); 3 GMaps.geocode({ 4 address: address, 5 callback: function( response, status ) { 6 return dfd.resolve( response ); 7 } 8 }); 9 return dfd.promise(); 10 }; 11 var getRoute = function( fromLatLng, toLatLng ) { 12 var dfd = new $.Deferred(); 13 map.getRoutes({ 14 origin: [ fromLatLng.lat(), fromLatLng.lng() ], 15 destination: [ toLatLng.lat(), toLatLng.lng() ], 16 travelMode: "driving", 17 unitSystem: "imperial", 18 callback: function( e ) { 19 return dfd.resolve( e ); 20 } 21 }); 22 return dfd.promise(); 23 }; 24 var doSomethingCoolWithDirections = function( route ) { 25 // do something with route 26 }; 27 $.when( geocode( fromAddress ), geocode( toAddress ) ). 28 then(function( fromLatLng, toLatLng ) { 29 getRoute( fromLatLng, toLatLng ).then( doSomethingCoolWithDirections ); 30 });
这允许你执行两个异步函数后,等待它们的结果,之后再用先前两个调用的结果来执行另外一个函数。
promise表示一个操作独立完成后返回的最终结果。
在这段代码里,geocode方法执行了两次并返回了一个promise。异步函数之后执行,并在其回调里调用了resolve。然后,一旦两次调用resolve完成,then将会执行,其接收了之前两次调用geocode的返回结果。结果之后被传入getRoute,此方法也返回一个promise。最终,当getRoute的promise解决后,doSomethingCoolWithDirections回调就执行了。
事件
事件是另一种当异步回调完成处理后的通讯方式。一个对象可以成为发射器并派发事件,而另外的对象则监听这些事件。这种类型的事件处理方式称之为 观察者模式 。 backbone.js 库在withBackbone.Events中就创建了这样的功能模块。
1 var SomeModel = Backbone.Model.extend({ 2 url: "/someurl" 3 }); 4 var SomeView = Backbone.View.extend({ 5 initialize: function() { 6 this.model.on( "reset", this.render, this ); 7 this.model.fetch(); 8 }, 9 render: function( data ) { 10 // do something with data 11 } 12 }); 13 var view = new SomeView({ 14 model: new SomeModel() 15 });
还有其他用于发射事件的混合例子和函数库,例如 jQuery Event Emitter , EventEmitter , monologue.js ,以及node.js内建的 EventEmitter 模块。
事件循环是一个回调函数的队列。
一个类似的派发消息的方式称为 中介者模式 , postal.js 库中用的即是这种方式。在中介者模式,有一个用于所有对象监听和派发事件的中间人。在这种模式下,一个对象不与另外的对象产生直接联系,从而使得对象间都互相分离。
绝不要返回promise到一个公用的API。这不仅关系到了API用户对promises的使用,也使得重构更加困难。不过,内部用途的promises和外部接口的事件的结合,却可以让应用更低耦合且便于测试。
在先前的例子里面,doSomethingCoolWithDirections回调函数在两个geocode函数完成后执行。然后,doSomethingCoolWithDirections才会获得从getRoute接收到的响应,再将其作为消息发送出去。
1 var doSomethingCoolWithDirections = function( route ) { 2 postal.channel( "ui" ).publish( "directions.done", { 3 route: route 4 }); 5 };
这允许了应用的其他部分不需要直接引用产生请求的对象,就可以响应异步回调。而在取得命令时,很可能页面的好多区域都需要更新。在一个典型的jQuery Ajax过程中,当接收到的命令变化时,要顺利的回调可能就得做相应的调整了。这可能会使得代码难以维护,但通过使用消息,处理UI多个区域的更新就会简单得多了。
1 var UI = function() { 2 this.channel = postal.channel( "ui" ); 3 this.channel.subscribe( "directions.done", this.updateDirections ).withContext( this ); 4 }; 5 UI.prototype.updateDirections = function( data ) { 6 // The route is available on data.route, now just update the UI 7 }; 8 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吧 !