js 封装promise
时间: 2023-05-16 10:06:55 浏览: 113
JS 封装 Promise 的方法有很多种,以下是一种常见的封装方法:
```javascript
function myPromise(fn) {
let state = 'pending';
let value = null;
let callbacks = [];
this.then = function(onFulfilled) {
return new myPromise(function(resolve) {
handle({
onFulfilled: onFulfilled || null,
resolve: resolve
});
});
};
function handle(callback) {
if (state === 'pending') {
callbacks.push(callback);
return;
}
if (!callback.onFulfilled) {
callback.resolve(value);
return;
}
let ret = callback.onFulfilled(value);
callback.resolve(ret);
}
function resolve(newValue) {
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
let then = newValue.then;
if (typeof then === 'function') {
then.call(newValue, resolve);
return;
}
}
state = 'fulfilled';
value = newValue;
setTimeout(function() {
callbacks.forEach(function(callback) {
handle(callback);
});
}, 0);
}
fn(resolve);
}
```
这是一个简单的 Promise 封装,可以通过 `then` 方法链式调用。
阅读全文