基本使用方法
1、定义Promise异步执行代码块,获取数据捕获错误
function getJSON(){
return new Promise((resolve,reject)=>{
const request = new XMLHttpRequest();
request.open("GET",url)
request.onload = function(){
try{
if(this.status === 200){
resolve(JSON.parse(this.response));
}else{
reject(this.statusText)
}
}catch (e){
reject(e.message)
}
}
request.onerror = function(){
reject(this.status+":"+this.statusText)
}
request.send()
})
}
2、使用数据获取错误提示
getJSON("data/data.json").then(data => {
console.log(data)
}).catch( e => console.log(e))
以上对Promise的使用和普通回调函数区别不大,主要应用
1、 优化回调金字塔
getJSON("data/data1.json",function(err,data1){
getJSON(data1[0].location,function(err,locationInfor){
getJSON(locationInfor.location,function(err,Infor){
handle(Infor)
}
})
})
链式调用Promise
getJSON("data/data1.json")
.then(data1 => getJSON(data1[0].location))
.then(locationInfor => getJSON(locationInfor.location)
.then(Infor => handle(Infor))
.catch(err => console.log(err))
2、 集中处理多个独立异步任务
Promise.all([
getJSON("data/name.json"),
getJSON("data/age.json"),
getJSON("data/gender.json")
]).then(results => {
const name = results[0], age = results[1], gender = results[2];
}).catch(err => console.log(err))
与生成器结合使用
传入生成器,迭代Promise传递结果参数
function async(generator){
var iterator = generator();
try{
handle(iterator.next());
}catch(e){
iterator.throw(e)
}
fuction handle(iteratorResult){
if(iteratorResult.done){return;}
const iteratorValue = iteratorResult.value;
if(iteratorValue instanceof Promise){
iteratorValue.then(res => handle(iterator.next(res)))
.catch(err => iterator.throw(err))
})
}
}
}
传入生成器
async(function*(){
try{
const name = yield getJSON("data/name.json");
const age = yield getJSON(name[0].location);
}catch(e){}
})