javascript的非阻塞方式就是很酷,但也会带来很大麻烦,那就是会造成函数的多层嵌套,列如:
$.ajax(.....,function(callback){
$.ajax(.....,function(anothercall){
$.ajax(....function(...)){....}
})
});
以上代码的写法虽然合情合理但对代码的易读性和维护性造成很大伤害,估计会把看代码的人看昏倒。
也许你会问,可不可以把异步调用改为同步阻塞执行,很可惜在javascript里这似乎很难做到,请看 :
http://salehenrahman.wordpress.com/2012/06/04/javascript-cant-synchronize-asynchronous-code/
于是,就有人提出了Promise模式,
http://wiki.commonjs.org/wiki/Promises/A
“which represents the result of a potentially long running and not necessarily complete operation. Instead of blocking and waiting for the long-running computation to complete, the pattern returns an object which represents the promised result.”
这个翻译好像不是很直观 , 但Promise模式的目的就是把回调函数们用一种顺序流的方式表达出来, 引入了then,when,done等链式函数,
增加可读性, 如以下代码 :
$.ajax(.....,function(callback){ }).then( $.ajax(.....,function(callback){ } ).then( $.ajax(.....,function(anothercall){ $.ajax(....function(...)){....} }) )
先介绍到这里,这里是jQuery(>1.5)的promise模式参考 :
http://api.jquery.com/category/deferred-object/