手写 Promise
时间: 2023-10-20 16:31:01 浏览: 138
手写promise,实现
当然可以!以下是一个简单的手写Promise的示例:
```javascript
class Promise {
constructor(executor) {
this.state = 'pending';
this.value = undefined;
this.reason = undefined;
this.onResolveCallbacks = [];
this.onRejectCallbacks = [];
const resolve = (value) => {
if (this.state === 'pending') {
this.state = 'fulfilled';
this.value = value;
this.onResolveCallbacks.forEach(callback => callback());
}
};
const reject = (reason) => {
if (this.state === 'pending') {
this.state = 'rejected';
this.reason = reason;
this.onRejectCallbacks.forEach(callback => callback());
}
};
try {
executor(resolve, reject);
} catch (error) {
reject(error);
}
}
then(onFulfilled, onRejected) {
const fulfilledHandler = typeof onFulfilled === 'function' ? onFulfilled : value => value;
const rejectedHandler = typeof onRejected === 'function' ? onRejected : reason => { throw reason; };
const promise2 = new Promise((resolve, reject) => {
const fulfillHandlerWrapper = () => {
setTimeout(() => {
try {
const result = fulfilledHandler(this.value);
resolvePromise(promise2, result, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
};
const rejectHandlerWrapper = () => {
setTimeout(() => {
try {
const result = rejectedHandler(this.reason);
resolvePromise(promise2, result, resolve, reject);
} catch (error) {
reject(error);
}
}, 0);
};
if (this.state === 'fulfilled') {
fulfillHandlerWrapper();
} else if (this.state === 'rejected') {
rejectHandlerWrapper();
} else {
this.onResolveCallbacks.push(fulfillHandlerWrapper);
this.onRejectCallbacks.push(rejectHandlerWrapper);
}
});
return promise2;
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
function resolvePromise(promise, result, resolve, reject) {
if (promise === result) {
return reject(new TypeError('Chaining cycle detected for promise'));
}
let thenCalledOrThrow = false;
if (result instanceof Promise) {
result.then(
value => resolvePromise(promise, value, resolve, reject),
reason => reject(reason)
);
} else if (result !== null && (typeof result === 'object' || typeof result === 'function')) {
try {
const then = result.then;
if (typeof then === 'function') {
then.call(
result,
value => {
if (thenCalledOrThrow) return;
thenCalledOrThrow = true;
resolvePromise(promise, value, resolve, reject);
},
reason => {
if (thenCalledOrThrow) return;
thenCalledOrThrow = true;
reject(reason);
}
);
} else {
resolve(result);
}
} catch (error) {
if (thenCalledOrThrow) return;
thenCalledOrThrow = true;
reject(error);
}
} else {
resolve(result);
}
}
```
这只是一个基本的实现,还有很多细节和功能可以改进。希望对你有所帮助!
阅读全文