Promise 实现与链式调用
处理异步
在处理异步操作时,当Promise
处于FULFILLED
状态时,我们需要保存传入的函数,并订阅onFulfilled
和onRejected
。当状态发生变化时,再执行已保存的方法。
const PENDING = 'PENDING';
const FULFILLED = 'FULFILLED';
const REJECTED = 'REJECTED';
class MyPromise {
constructor(executor) {
this.status = PENDING;
this.value = undefined;
this.reason = undefined;
this.onFulfilledCallbacks = [];
this.onRejectedCallbacks = [];
const resolve = (value) => {
if (this.status === PENDING) {
this.status = FULFILLED;
this.value = value;
this.onFulfilledCallbacks.forEach((callback) => callback());
}
};
const reject = (reason) => {
if (this.status === PENDING) {
this.status = REJECTED;
this.reason = reason;
this.onRejectedCallbacks.forEach((callback) => callback());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
if (this.status === FULFILLED && typeof onFulfilled === 'function') {
onFulfilled(this.value);
}
if (this.status === REJECTED && typeof onRejected === 'function') {
onRejected(this.reason);
}
if (this.status === PENDING) {
if (typeof onFulfilled === 'function') {
this.onFulfilledCallbacks.push(() => onFulfilled(this.value));
}
if (typeof onRejected === 'function') {
this.onRejectedCallbacks.push(() => onRejected(this.reason));
}
}
return this;
}
}
链式调用
成功的条件
then
方法返回一个新的Promise
,当以下条件满足时,新的Promise
将处于成功状态:
返回一个普通的JavaScript
值。
返回一个成功态的新的Promise
,其值为value
。
失败的条件
当以下条件发生时,then
方法返回的新的Promise
将处于失败状态:
返回一个失败态的新的Promise
,其原因为reason
。
在then
方法内部抛出异常。
实现链式调用
为了实现链式调用,需要在then
方法中返回this
或返回一个新的Promise
实例。以下是实现链式调用的示例:
then(onFulfilled, onRejected) {
return new MyPromise((resolve, reject) => {
if (this.status === FULFILLED) {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
}
if (this.status === REJECTED) {
try {
const result = onRejected(this.reason);
resolve(result);
} catch (error) {
reject(error);
}
}
if (this.status === PENDING) {
this.onFulfilledCallbacks.push(() => {
try {
const result = onFulfilled(this.value);
resolve(result);
} catch (error) {
reject(error);
}
});
this.onRejectedCallbacks.push(() => {
try {
const result = onRejected(this.reason);
resolve(result);
} catch (error) {
reject(error);
}
});
}
});
}
通过返回一个新的Promise
实例,可以在then
方法后继续调用其他then
方法,实现链式调用。