class Promise {
constructor(executor) {
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
//存放成功的回调
this.onFulFilledCallbacks = [];
//存放失败的回调
this.onRejectedCallbacks = [];
let resolve = (value) => {
if (this.status == 'pending') {
this.status = 'fulfilled';
this.value = value;
this.onFulFilledCallbacks.forEach(fn => fn())
}
}
let reject = (err) => {
if (this.status == 'pending') {
this.status = 'rejected';
this.reason = err;
this.onRejectedCallbacks.forEach(fn => fn())
}
}
try {
executor(resolve, reject)
} catch (e) {
reject(e)
}
}
then(onFulFilled, onRejected) {
let promise2
if (this.status = 'fulfilled') {
promise2 = new Promise((resolve, reject) => {
let x = onFulFilled(this.value);
//解析promise2和x之间的关系
resolvePromise(promise2, x, resolve, reject)
})
}
if (this.status = 'rejected') {
promise2 = new Promise((resolve, reject) => {
let x = onRejected(this.reason);
resolvePromise(promise2, x, resolve, reject)
})
}
//异步调用时进不到resolve,状态始终为pending,此时可以先把callback存起来待到resolve或reject再逐一执行
if (this.status = 'pending') {
this.onFulFilledCallbacks.push(() => {
promise2 = new Promise((resolve, reject) => {
let x = onFulFilled(this.value)
resolvePromise(promise2, x, resolve, reject)
})
})
this.onRejectedCallbacks.push(() => {
promise2 = new Promise((resolve, reject) => {
let x = onRejected(this.reason)
resolvePromise(promise2, x, resolve, reject)
})
})
}
return promise2;
}
}
//判断x是不是promise,规范规定代码确定不同的promise间可以交互。
resolvePromise(promise2, x, resolve, reject) {
if (x === promise2) {
return reject(new TypeError('Chaining cycle detected for promise!'))
}
if (x !== null && typeof x == 'object' || typeof x == 'function') {
//防止取then时出现异常 Object.definedProperty
try {
if (typeof x == 'function') {
x.then.call(x, y => {
resolvePromise(promise2, y, resolve, reject)
})
} else {
resolve(x)
}
} catch (e) {
reject(e)
}
} else {
resolve(x)
}
}
网友评论