Promise

Promise是一门新的技术(ES6规范),Promis是JS中进行异步编程的新解决方案(旧方案是单纯使用回调函数)

优点:

  • 指定回调函数的方式更加灵活
  • 支持链式调用,可以解决回调地狱问题

Promise的状态改变

promise的状态为实例对象中的一个属性[PromiseState]

1.pending(初始状态)变为resolved
2.pending(初始状态)变为rejected

说明:只有这2种,且一个promise对象只能改变一次无论变为成功还是失败都会有一个结果数据成功的结果数据一般称为value,失败的结果数据一般称为reason

Promise的工作流程

相关Api

Promise(excutor){}

  • executor:(resolve,reject)=>{}
  • resolve函数:内部定义成功时调用的函数value=>{}
  • reject函数:内部定义失败时我们调用的函数reason=>{}

Promise.prototype.then 方法:(onResolved,onRejected)=>{}

  • onResolved函数:成功的回调函数(value)=>{}
  • onRejected函数:失败的回调函数(reason)=>{}

Promise.prototype.catch方法:(onRejected)=>{}

  • onRejected函数:失败的回调函数(reason)=>{}

Promise.resolve 方法:(value)=>{}

  • value:成功的数据或promise对象

Promise.reject方法:(reason)=>{}

  • reason:失败的原因

Promise.all方法:(promise)=>{}

  • promises:包含n个promise的数组
  • 返回一个新的promise,只有所有promise都成功才成功,只要有一个失败就直接失败

Promise.race方法:(promise)=>{}

  • promises:包含n个promise的数组
  • 返回一个新的promise,第一个完成的promise的结果就是最终的结果状态

初体验

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
//resolve、reject函数类型的数据
const p = new Promise((resolve,reject) => {
setTimeout(() => {
let n = rand(1,100);
if(n <= 30){
resolve(n); //将promise对象得状态为成功
}else{
reject(n); //将promise对象得状态为失败
}
},1000);
});
//调用then方法指定异步回调
p.then((value)=> { //成功时的回调
alert(value+"成功");
},(reason) => {
alert(reason+"失败");
})

发送ajax请求

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
const btn = document.getElementsByTagName("button");
btn.addEventListener('click',function(){
const p = new Promise((resolve,reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET','https://api.apiopen.top/getJoke');
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
resolve(xhr.response);
}else{
reject(xhr.status);
}
}
}
})
p.then(value=>{
console.log(value);
},reason=>{
console.log(reason);
})
});

async函数

  1. 函数的返回值为promise对象

  2. promise对象的结果由async函数执行的返回值决定

1
2
3
4
async function main(){
//return 111; 返回非promise数据则返回成功的promise
return new Promise((resolve,reject)=>{}) //返回与该promise的状态一致的promise
}

await表达式

  1. await右侧的表达式一般为promise对象,但也可以是其它的凰
  2. 如果表达式是promise对象,await返回的是promise成功的值
  3. 如果表达式是其它值,直接将此值作为await的返回值

async和await结合发送ajxa

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
const btn = document.getElementsByTagName("button");
function sendAjax(url){
return new Promise((resolve,reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET',url);
xhr.send();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
if(xhr.status >= 200 && xhr.status < 300){
resolve(xhr.response);
}else{
reject(xhr.status);
}
}
}
})
}
btn.addEventListener('click',async function(){
let dunzi = await sendAjax('https://api.apiopen.top/getJoke');
alert(dunzi);
});