复习之前的
catch方法
time 18m55s
catch(onRejected) {
return this.then(null, onRejected);
}
resolve方法
time 20m03s
time 30
time 43m
测试方法
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => {
reject('1000');
}, 3000)
})
MyPromise.resolve(p1)
.then(res => console.log(res, 'success')
, err => console.log(err, 'fail')
)
1000 fail
/**
* 判断值是否是promise对象,thanable对象
* @param value 参数,在这里是回调函数,比如promise.resolve的参数,可能是函数,
* 可能是promise对象
* @returns {boolean} 是否是promise对象,thenable对象
*/
const isPromsie = (value) => typeof value.then === "function";
static resolve(value) {
if (isPromsie(value)) {
return value;
} else {
return new MyPromise((resolve, reject) => {
resolve(value)
})
}
}
当时promise对象时,返回promise对象value,当不是时返回经过包装的promise对象
const p1 = new MyPromise((resolve, reject) => {
setTimeout(() => {
reject(new MyPromise((resolve, reject) => {
setTimeout(()=>{
reject('1000');
},3000)
}));
}, 3000)
})
MyPromise.resolve(p1)
.then(res => console.log(res, 'success')
, err => console.log(err, 'fail')
)
static resolve(value) {
return new MyPromise((resolve, reject) => {
resolve(value)
})
}
把isPromsie放到resolve中
let resolve = (value) => {
if (this.state === 'pending') {
/*time 43m*/
if (isPromsie(value)) {
/*递归调用,继续resolve,如果是reject走reject
* value是promise,但最终还是得resolve或reject,所以得用then
* 运行,为了运行resolve、或者reject,通过then取出promise对象value
* 中的值,再进行resolve或者reject,reject是不能运行一个promise对象的*/
value.then(data => resolve(data), err => reject(err));
} else {
this.state = 'fullFilled';
this.value = value;
// this.onFullFilledCallbacks.forEach(fn => fn(this.value));
this.onFullFilledCallbacks.forEach(fn => fn());
}
}
}
finally
time 49m