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就好了