JQuery中Deferred/Promise的使用

同样Deferred也是为了解决异步嵌套回调而存在的。早在JQuery 1.5就已经支持了。

使用方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var dtd = $.Deferred(); // 新建一个Deferred对象
var wait = function(dtd){
var tasks = function(){
      alert("执行完毕!");
      dtd.resolve(); // 改变Deferred对象的执行状态
    };
    setTimeout(tasks,5000);
    return dtd.promise(); // 返回promise对象
  };
var d = wait(dtd); // 新建一个d对象,改为对这个对象进行操作
$.when(d)
.done(function(){ alert("哈哈,成功了!"); })
.fail(function(){ alert("出错啦!"); });

我们看下怎么样用,下面列举了几个场景:

  1. 单个Ajax异步交互
1
2
3
4
5
$.ajax('abc.php').done(function(result) {
alert('success');
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log('error');
});
  1. 多个Ajax异步交互
1
2
3
4
5
6
$.when($.ajax('abc.php'), $.ajax('abc2.php'), $.ajax('abc3.php'))
.done(function(result1, result2, result3) {
alert('success');
}).fail(function (jqXHR, textStatus, errorThrown) {
console.log('error');
});
  1. 动画链式调用
1
2
3
4
5
6
7
8
9
$.when(preloadImage())
.then(animation01)
.then(animation02)
.then(animation03)
.then(transition)
.then(merge)
.then(zoom)
.then(showContent)
.then(flicker);

和Promise/A+的规范有些出入,可能因为实现比较早,但是其意义和原理是差不多的。