Promise處理有依賴的連續請求
在沒有接觸到Promise之前,如果有這樣的需求,先去前端需要異步去請求第一個接口,然後接收到返回的一些數據,然後利用得到的數據,去請求第二個接口,然後接收傳回來的數據,然後去請求第三個接口,這個時候我自己寫出來的代碼一定是Ajax嵌套的一堆,寫出來的代碼可想而知,真的是太醜。
我現在不敢說我對Promise有多懂,因爲我離靈活應用它,還有距離,最近在看書,偶然看到了Promise這個東西,所以忍不住想要去嘗試
亂糟糟的代碼
$.ajax({
url: '/union/perfomace/getPeformanceName',
type: 'POST',
dataType: 'json',
contentType: 'application/json'
}).then(function(re) {
$.ajax({
url: '/union/perfomace/getPeformancePlan',
type: 'POST',
dataType: 'json',
data: {peformanceName: re.peformanceName[0]},
contentType: 'application/json'
}).then(function(re) {
$.ajax({
url: '/union/hall/getHallInfo',
type: 'POST',
dataType: 'json',
data: {plan: re.plans[0]},
contentType: 'application/json'
}).then(function(re) {
....
})
})
})
當然,也許你寫的會比我的好看
promise的改寫
function request(url, data) {
return new Promise(function(resolve, reject) {
$.ajax({
url: url,
contentType: 'json',
data: data,
success: function(resData) {
resolve(resData);
}
})
})
}
request("/union/perfomace/getPeformanceName", {})
.then(function(response1) {
return request('/union/perfomace/getPeformancePlan', {peformanceName: response1.peformanceName[0]});
})
.then(function(response2) {
return request('/union/hall/getHallInfo', {plan: response2.plans[0]});
});
是不是感覺好多了,反正我是覺得看着舒服多了,下面我把上面的代碼分析下吧
首先,request這個函數的作用就是返回一個promise對象,它裏面的resolve第一次的時候是第一個then裏面的函數,第二次的時候是第二個then裏面的函數,需要給這個該函數傳入url和data對象,以便發送正確請求
當第一次調用request函數的時候,返回的是一個promise對象,其實在then裏面的函數如果不通過return返回一個promise的時候,它其實也是返回了一個新的promise的,當這個return返回的非promise的時候,返回的就是一個promiseValue等於返回值的Promise,在返回值爲promise的時候,當然直接返回這個promise就好了