# 回調地獄
- 由於$.ajax()嵌套過多,致使回調地獄,造成三角形代碼
```js
$.ajax({
url: 'https://www.baidu.com',//隨便寫的地址,不能使用
type: 'GET',
success: function (res) {
$.ajax({
url: 'https://www.taobao.com',//隨便寫的地址,不能使用
type: 'GET',
data: {
accountId: 20200515
},
success:function(res){
$.ajax({
url: 'https://www.tencent.com',//隨便寫的地址,不能使用
type: 'GET',
data: {
accountId: 20200515
},
success:function(res){
$.ajax({
url: 'https://www.douban.com',//隨便寫的地址,不能使用
type: 'GET',
data: {
accountId: 20200515
},
success:function(res){
console.log(res);
}
});
}
});
}
});
}
});
```
- $.Deferred()//延遲對象
```js
//作一件異步的事情
function createScore(){
var df = $.Deferred();
setInterval(function(){
var score = Math.random() * 100;
if(score > 90){
df.resolve('經過');//觸發done()
}else if(score < 80){
df.reject('未經過');//觸發reject()
}else{
df.notify('請耐心等候');//觸發progress()
}
}, 1500);
//df.promise()返回一個閹割版的df對象,只能調用done fail progress三個方法
return df.promise();
}
//延遲對象
var df = createScore();
// done:成功; fail:失敗; progress:正在進行;
// resolve; reject; notify;
df.done(function(ms){//註冊成功的回調函數
console.log("成功" + ' ' + ms);
}).fail(function(ms){//註冊失敗的回調函數
console.log("失敗" + ' ' + ms);
}).progress(function(ms){//註冊進行的回調函數
console.log("等待......" + ' ' + ms);
});
```
- $.Deferred().then()
```js
//作一件異步的事情
function createScore(){
var df = $.Deferred();
setInterval(function(){
var score = Math.random() * 100;
if(score > 90){
df.resolve('經過');//觸發done()
}else if(score < 80){
df.reject('未經過');//觸發reject()
}else{
df.notify('請耐心等候');//觸發progress()
}
}, 1500);
//df.promise()返回一個閹割版的df對象,只能調用done fail progress三個方法
return df.promise();
}
//延遲對象
var df = createScore();
// done:成功; fail:失敗; progress:正在進行;
// resolve; reject; notify;
df.then(
function(){//註冊成功的回調函數
var df = $.Deferred();
setTimeout(function(){
df.resolve("成功");
}, 1500);
return df.promise();
}, function(){//註冊失敗的回調函數
var df = $.Deferred();
setTimeout(function(){
df.resolve("失敗");
}, 1500);
return df.promise();
},function(){//註冊進行的回調函數
var df = $.Deferred();
setTimeout(function(){
df.resolve("等待......");
}, 1500);
return df.promise();
}
).then(
function(ms){//註冊成功的回調函數
console.log(ms + "resolve");
}, function(ms){//註冊失敗的回調函數
console.log(ms + "reject");
}, function(ms){//註冊進行的回調函數
console.log(ms + "notify");
}
);
```
## 使用then解決回調地獄
```js
(function(){
return $.ajax({
url: 'https://www.baidu.com',//隨便寫的地址,不能使用
type: 'GET'
});
})().then(function(res){//成功
if(res.data.msg == 'success'){
var df = $.Deferred();
$.each(res.data.arr, function(index, ele){
var $btn = $("button");
$btn.on('click', function(){
df.resolve(this);
});
});
return df.promise();
}
}).then(function(res){//成功
res.css({width:'100px',height:'100px',background:'red'});
return $.ajax({
url: 'https://www.tencent.com',//隨便寫的地址,不能使用
type: 'GET'
});
}).then(function(res){//成功
return $.ajax({
url: 'https://www.douban.com',//隨便寫的地址,不能使用
type: 'GET'
});
});
```