1.promise的几种状态及状态的切换
2.then和catch的返回值
1.promise的三种状态
- pending fulfilled rejected
2.触发状态的
pending -->fulfilled
pending -->rejected
变化的状态是不可逆的,一旦变化就不会返回。
3.then和catch对状态的影响 (then和catch的链式调用)
1 状态的变化
1-1 pending 冻结
var p = new Promise((resolve,reject)=>{
})
console.log(p)
1-2 pending - resolve
var p = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve()
})
})
console.log(p)
setTimeout(()=>{
console.log(p)
})
2 触发状态状
1.pending状态不会触发resolve和reject
2.resolve会触发之后的then回调函数
3.reject会触发catch回调函数
var p = Promise.resolve(100);
var r = Promise.reject(200);
3 then和catch改变状态 返回值
1.then正常返回resolve,有报错则返回reject
2.catch正常返回resolve,有报错则返回reject
3-1 pending —>resolve
var p = Promise.resolve(100).then(res=>{
console.log(res)
})
console.log(p) //返回
//没有报错可以继续then
p.then(()=>{
console.log(200)
})
3-2 then函数中有报错,返回reject
var p = Promise.resolve(100).then(res=>{
console.log(res)
throw "不是函数"
})
console.log(p)
3-3 有报错继续then函数
var p = Promise.resolve(100).then(res=>{
throw "error"
})
p.then(()=>{
console.log("good")
}).catch(res=>{
console.log(res)
})
3-4 catch之报错
var p = Promise.reject("err").catch(err=>{
console.log(err)
throw "fun"
})
console.log(p) //返回的promise的状态为 reject