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)
}
}
Promise的实现
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...