javascript的Promise模式 1.起源

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/

 

 

转载于:https://www.cnblogs.com/Yesky93/archive/2013/04/08/3008372.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值