【JavaScript】新手如何手写Promise
|
admin
2024年12月25日 10:19
本文热度 839
|
一、Promise是个啥?
Promise是JavaScript中用于处理异步操作的对象,代表一个异步操作的最终完成(或失败)及其结果值。它有三种状态: pending (进行中)、 fulfilled (已成功)和 rejected (已失败)。状态一旦改变,就不会再变。
二、手写Promise基本结构
function MyPromise(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
const resolveCallbacks = [];
const rejectCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
resolveCallbacks.forEach(callback => callback());
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state ='rejected';
this.reason = reason;
rejectCallbacks.forEach(callback => callback());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
三、实现then方法
then 方法用于为Promise添加成功和失败回调。
MyPromise.prototype.then = function (onFulfilled, onRejected) {
onFulfilled = typeof onFulfilled === 'function'? onFulfilled : value => value;
onRejected = typeof onRejected === 'function'? onRejected : reason => { throw reason };
return new MyPromise((resolve, reject) => {
if (this.state === 'fulfilled') {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(resolve, reject, x);
} catch (error) {
reject(error);
}
});
}
if (this.state ==='rejected') {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(resolve, reject, x);
} catch (error) {
reject(error);
}
});
}
if (this.state === 'pending') {
this.resolveCallbacks.push(() => {
setTimeout(() => {
try {
const x = onFulfilled(this.value);
resolvePromise(resolve, reject, x);
} catch (error) {
reject(error);
}
});
});
this.rejectCallbacks.push(() => {
setTimeout(() => {
try {
const x = onRejected(this.reason);
resolvePromise(resolve, reject, x);
} catch (error) {
reject(error);
}
});
});
}
});
};
四、辅助函数resolvePromise
处理 then 回调返回值的逻辑。
function resolvePromise(resolve, reject, x) {
if (x === resolvePromise) {
return reject(new TypeError('Chaining cycle detected for promise'));
}
let called = false;
if (x!== null && (typeof x === 'object' || typeof x === 'function')) {
try {
const then = x.then;
if (typeof then === 'function') {
then.call(x, y => {
if (called) return;
called = true;
resolvePromise(resolve, reject, y);
}, r => {
if (called) return;
called = true;
reject(r);
});
} else {
resolve(x);
}
} catch (error) {
if (called) return;
called = true;
reject(error);
}
} else {
resolve(x);
}
}
五、测试MyPromise
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('Success!');
}, 1000);
});
promise.then(value => {
console.log(value);
return 'New value';
}).then(newValue => {
console.log(newValue);
});
OK 到这里一个简单的手写Promise就实现了,涵盖了Promise的基本状态管理、 then 方法及处理回调返回值的逻辑。
该文章在 2024/12/25 10:19:24 编辑过