promise连续流程请求
不使用promise的情况
$.ajax({
url: '/first',
type: 'POST',
dataType: 'json',
contentType: 'application/json'
}).then(function(res) {
$.ajax({
url: '/second',
type: 'POST',
dataType: 'json',
data: {second: 2},
contentType: 'application/json'
}).then(function(res) {
....
})
})
})
如上,我们可以看到代码非常凌乱。
使用psomise的情况
function request(url, data) {
return new Promise(function(resolve, reject) {
$.ajax({
url: url,
contentType: 'json',
data: data,
success: function(resData) {
resolve(resData);
}
})
})
}
request('/first', {})
.then(function(response1) {
return request('/second', {second:2});
})
.then(function(response2) {
...
});
如上,这样代码就一目了然了。
本文借鉴 Dear_Mr 的CSDN 博客 ,全文地址请点击:https://blog.csdn.net/Dear_Mr/article/details/78871352?utm_source=copy