Promise
- status
状态,有三种状态pendding、resolved、rejected,状态由 pending->resolved/rejected,不可逆
- resolve
resolve 方法,修改 promise 的状态为 resolved,执行 resolve 回调
- reject
reject 方法,修改 promise 的状态为 rejected,并执行 reject 的回调
- then
用于 promise 链式调用,返回一个新的 Promise 对象
常规使用方法
const p = new Promise((resolve, reject) => {
// 执行一堆操作
resolve() // reject()
})
p.then(res => {
// 成功回调函数
}, err => {
// 失败回调函数
})
p.then(() => {}, () => {})
// then 方法会将成功回掉函数添加到 Promise 的成功回调队列,将失败回调函数添加到失败回调队列,一个 promise 对象可以调用多次 then 方法,并返回一个新的 Promise 对象,所以可以进行链式调用
链式调用
const p1 = new Promise((resolve, reject) => {
resolve(1)
})
const p2 = new Promise((resolve, reject) => {
resolve(2)
})
p1.then(res => { // 第一次调用 then
console.log(res) // 1
return p2
}).then(res => { // 第二次调用 then
console.log(res) // 2
})
// 思考, 为什么 第二次调用 then 里面的成功回调函数的参数值会是p2的 resolve的值?
// then返回值具体规则
/*
- 如果返回一个值,则 then 返回的 Promise 状态成为 resolved,并且返回的值作为回调的参数值
- 若没有返回值,则状态为 resolved,参数值为 undefined
- 若回调函数抛出错误,则为 rejected,抛出的错误为拒绝状态的参数值
- 若返回 promise 对象,则状态与该 promise 状态一致,并且回调函数的参数值为该 promise 的状态参数值。
*/
p1.then(res => {
return 'return value'
}).then (res => {
console.log(res) // 'return value'
}).then(res => {
console.log(res) // undefined
return p2
}).then(res => {
console.log(res) // 2
console.log(undefined.name)
}, err => {
console.log(err) //不会执行
})
.then(res => {}, err => {
console.log(err) // TypeError: Cannot read property 'name' of undefined
return 'err'
})
.catch(err => {
console.log(err) // 不会执行
})
.then(res => {
console.log(res) // 'err'
console.log(undefined.name)
})
.then(res => {
console.log(res) // 不会执行
})
.catch(err => {
console.log(err) // TypeError: Cannot read property 'name' of undefined
})
// 关于promise catch 的执行,传递到最近一次的 catch 方法,
网友评论