用es5复写 Promise
时间: 2023-10-20 16:19:57 浏览: 95
好的,以下是使用 ES5 复写 Promise 的代码示例:
```javascript
function Promise(fn) {
var state = 'pending';
var value;
var deferred = null;
function resolve(newValue) {
if (newValue && typeof newValue.then === 'function') {
newValue.then(resolve);
return;
}
value = newValue;
state = 'resolved';
if (deferred) {
handle(deferred);
}
}
function reject(reason) {
state = 'rejected';
value = reason;
if (deferred) {
handle(deferred);
}
}
function handle(handler) {
if (state === 'pending') {
deferred = handler;
return;
}
var handlerCallback;
if (state === 'resolved') {
handlerCallback = handler.onResolved;
} else {
handlerCallback = handler.onRejected;
}
if (!handlerCallback) {
if (state === 'resolved') {
handler.resolve(value);
} else {
handler.reject(value);
}
return;
}
var ret;
try {
ret = handlerCallback(value);
} catch (e) {
handler.reject(e);
return;
}
handler.resolve(ret);
}
this.then = function(onResolved, onRejected) {
return new Promise(function(resolve, reject) {
handle({
onResolved: onResolved,
onRejected: onRejected,
resolve: resolve,
reject: reject
});
});
};
fn(resolve, reject);
}
```
上述代码是一个最基本的 Promise 实现,支持 `then` 方法,但没有支持 `catch` 和 `finally` 方法,也没有提供 `Promise.resolve` 和 `Promise.reject` 静态方法。同时,这个实现中还没有处理异步行为,所以是不完整的。
阅读全文