promise的状态改变
- pending变成resolved
- pending变成rejected
说明:只有这两种,且一个promise对象只能改变一次,
无论变成成功还是失败,都会有一个结果数据,
成功的结果数据一般称为value,失败的结果数据一般称为reason
如何使用Promise
- Promise构造函数:Promise(excutor){}
- excutor函数:执行器(resolve,reject)=>{}
- resolve函数:内部定义成功时我们调用的函数value=>{}
- reject函数:内部定义失败时我们调用的函数 reason=>{}
- 流程(封装定时器):
//1)创建promise对象(pending状态),指定执行器函数
const p=new Promise((resolve,reject)=>{
//2)在执行器函数中启动异步任务
setTimeout(()=>{
//3)根据结果做不同处理
const time=Date.now()
// 3.1)如果成功了,调用resolve(),指定成功的value,变成resolved状态
if (time%2==1){
resolve('成功的数据'+time)
}else{
// 3.2)如果失败了,调用reject(),指定失败的reason,变成rejected状态
reject('失败的数据'+time)
}
},1000)
})
//4)能promise指定成功或失败的回调函数来获取成功的value或者失败的reason
p.then(
value=>{
console.log('成功',value)
},
reason=>{
console.log('失败',reason)
}
)
使用promise封装ajax
function ajaxPromise(url){
return new Promise((resolve,reject)=>{
const xhr=new XMLHttpRequest();
xhr.open('GET',url)
xhr.send()
xhr.onreadystatechange=function(){
if (xhr.state!=4) return
if (xhr.status>=200&&xhr.status<300){
resolve(JSON.parse(xhr.response))
}else{
reject(new Error(JSON.parse(xhr.response)))
}
}
})
}
ajaxPromise('http://xxxx:9000')
.then(
value=>{
console.log('调用成功',value)
},
reason=>{
console.log('调用失败',reason)
}
)