1. catch方法的实现
在实现了then方法后,实现catch方法较为简单,只需调用then方法,第一个参数为undefined,第二个参数传入失败的回调函数即可
/*
为 promise 指定失败的回调函数
是 then(null, onRejected)的语法糖
*/
Promise.prototype.catch = function (onRejected) {
return this.then(undefined, onRejected);
}
1.1 实现异常穿透功能
当多个then方法链式调用时,其中任意一个then方法返回的Promise实例状态为rejected
时,都能被最后的catch方法捕捉到,我们称为异常穿透。
例如:
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('1')
}, 0)
})
p.then(value => {
console.log(value)
}).then(value => {
console.log(value)
throw '失败了'
}).then(value => {
console.log(value)
}).catch(reason => {
console.log(reason) // '失败了'
})
实现原理:当then方法第二个参数没有传入或不为函数时,需默认指定一个能将当前then方法返回的Promise实例状态改为rejected
,并传递错误结果
Promise.prototype.then = function (onResolved, onRejected) {
// 完成异常穿透功能
if(typeof onRejected !== 'function') {
onRejected = function(reason) {
throw reason
}
}
}
1.2 处理then方法参数为空情况
当then方法参数为空时,then方法会返回一个状态为fulfilled
的实例,结果值为调用then方法Promise实例的结果
例如:
let p = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('1')
}, 0)
})
p.then().then().then(value => {
console.log(value) // '1'
})
实现原理:当then方法第一个参数为空,或者不为函数时,需指定一个默认函数,该函数的作用是将then方法返回的Promise实例状态改为fulfilled
,并将接受的结果返回
if(typeof onResolved !== 'function') {
onResolved = function(value) {
return value
}
}