- promise它是什么?
- 它是一个ES6提出一个新语法,用来优化异步代码的写法 2.基本使用
let p = new Promise(function(resolve,reject){
//异步操作 resolve(res) 或者 reject(rej)
});
p.then(function(rs){
// 如果p的状态是resolved,则then中的函数
//会执行,且resolve的值会传给rs
}).catch(function(rs){
// 如果p的状态是reject,则catch中的函数
// 会执行,且reject的值会传给rs
}).finally(function(){
// 一定会执行的函数
})
3.构造器
- 构造器必须要给参数
- 这个参数是一个回调函数,有两个形参对应着成功状态和失败状态
- 函数体中执行异步代码
let p = new Promise((res, rej) => {
})
//状态不可逆
p.then(re => {
//成功时,走这里(resolved)
//状态pending-->fulfilled
}).catch(re => {
//失败时,走这里(rejected)
//状态pending-->rejected
}).finally(() => {
//一定执行这里
})
- 三种状态
- pending(等待状态):起始状态
- resolved(成功状态):也可以是fulfilled, 函数体中是 resolved参数
- rejected(失败状态):, 函数体中是 rejected参数
- 状态的转换
pending ----- resolve() --> resolved;
pending ----- reject() --> rejected;
状态转换是不可逆的。
- 看打印
- then
作用:是为Promise对象添加状态改变时的回调函数。
- then有两个参数,参数类型是函数
- 成功时,执行第一个参数
- 失败时,执行第二个参数(就是执行catch)
- 第二个参数是可选的
- 返回值是一个全新的promise对象
注意点:如果代码执行第二个参数,但没设置第二个参数时,会报错
- 返回值p.then的状态和值如何判断
var p1 = new Promise(()=>{});
var p2 = p1.then(function f_ok(){}, function f_err(){});
// p2是一个全新的promise对象。
console.log(p1 === p2); // false
- p1的状态是pending,则p2的状态也是pending。
- p1的状态是resolved,then()会去执行f_ok,则p2的状态由f_ok的返回值决定。
- p1的状态是rejected,then()会去执行f_err,则p2的状态由f_err的返回值决定。
当p1状态不是pending,则执行下面判断
- 返回值不是promise对象,则p2的状态是resolved,且p2的值就是p2返回值
- 返回值是promise对象,则p2的状态及值以这个promise对象为准。
- 函数内部发生了错误, 则p2的状态是rejected,且p2的值就是这个错误对象。
- async-await语法
- async,await 是es7中新增的语法,用来进一步改进异步代码的写法,是promise升级版!
- 解决回调地狱
async function fn() {
const res = await axios.get(url)
console.log(res)
const res1 = await axios.get(url+'?id=' + res.data[0].id)
console.log(res1)
const res2 = await axios.get(url+'?id=' + res1.data[0].id)
console.log(res2)
}
fn()
9.promise的all方法与race方法的区别
- 相等点:都可以将多个promise实例包装成一个新的promise实例
promise.all/race([promise1,promise2]).then(success,fail)
- 不同点:all需要两个promise都成功,而race只有一个成功就可以调用success