promise主要用来优雅的书写异步请求的层层嵌套,解放回调地狱。让代码看起来整洁,可读,易管理。
基本用法
var promise = new Promise(function(resolve, reject){
jQuery.ajax({
url: 'https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/api/order_list',
type: 'GET',
success: function(res){
if(res.result === '0000'){
resolve(res.data);//成功
}else {
reject(res.info);//失败
}
}
});
});
promise.then(function(data){
console.log(data)
}).catch(function(error){
console.error(error);
});
第二个请求参数依赖于第一个请求返回的数据
var ajaxPromise1 = function(){
return new Promise(function(resolve, reject){
jQuery.ajax({
url: 'https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/api/order_list',
type: 'GET',
success: function(res){
if(res.result === '0000'){
resolve(res.data[0]);
}else {
reject(res.info);
}
}
});
});
}
var ajaxPromise2 = function(data){
return new Promise(function(resolve, reject){
jQuery.ajax({
url: 'https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/api/order_list',
type: 'GET',
data: data,
dataType: 'json',
success: function(res){
if(res.result === '0000'){
console.log(res.data);
}else {
reject(res.info);
}
}
});
});
}
ajaxPromise1().then(ajaxPromise2);
Promise.all 解决ajax请求异步的问题,让多个异步请求依次返回对应数据
var ajaxPromise = function(url){
return new Promise(function(resolve, reject){
jQuery.ajax({
url: url,
type: 'GET',
success: function(res){
if(res.result === '0000'){
resolve(res.data);
}else {
reject(res.info);
}
}
});
});
}
Promise.all([ajaxPromise('https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/api/order_list'),
ajaxPromise('https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/api/order_list'),
ajaxPromise('https://www.easy-mock.com/mock/5b4eb12d56c59c6f56266215/api/order_list')])
.then((value)=>{
console.log(value); //依次返回的是1,2,3请求的数据
});
网友评论