一、基本用法
- promise有三种状态:初始化、成功、失败
const p = new Promise((resolve,reject)=>{ //接收两个函数参数分别为resolve,reject
setTimeout(()=>{
//若成功 则调用resolve函数,把P的状态改为成功
// let data = '数据库中的数据读取成功'
// resolve(data);
//若失败则调用reject函数,把P的状态为失败状态
let err = '数据读取失败'
resolve(err);
},1000);
});
//调用promise的then方法,也有两个函数参数,成功则执行第一个参数,不成功则执行第二个参数,根据P的状态来定
p.then(value=>{
console.log(value);
},err=>{
console.log(err);
})
二、promise封装Ajax请求
- 普通的ajax进行数据请求
三 、then方法的使用
- 基本用法
//then方法的返回结果也是一个Promise对象,对象状态由回调函数的执行结果决定
//若回调函数中的返回结果不是Promise类型的属性,状态为成功
const result=p.then(value=>{
console.log(value);
//不是Promise类型
// return 123;此处的回调函数中的返回结果就不是Promise类型的属性,状态为成功
//是promise类型
return new Promise((resolve,reject)=>{
// resolve('成功啦') 此时then 返回值也是成功
// reject('失败啦') 此时then 返回值也是失败
throw new Error('抛出错误')//此时也是失败
})
},err=>{
console.log(err);
})
- 链式调用
p.then(value=>{},error=>{}).then(value=>{},error=>{})
//也可以只写一种状态
p.then(value=>{}).then(value=>{})
四、catch方法
- 用来显示promise对象失败的方法