用js写一个promise源码
时间: 2024-03-21 22:19:33 浏览: 54
JS手写Promise源码
以下是一个基本的Promise源码实现。它包括Promise对象的构造函数以及then方法和catch方法的实现。该实现仅为示例,不是完整的Promise实现。
```
function Promise(fn) {
var state = 'pending';
var value;
var callbacks = [];
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle({
onFulfilled: onFulfilled || null,
onRejected: onRejected || null,
resolve: resolve,
reject: reject
});
});
};
this.catch = function(onError) {
return this.then(null, onError);
};
function handle(callback) {
if (state === 'pending') {
callbacks.push(callback);
return;
}
var cb = state === 'fulfilled' ? callback.onFulfilled : callback.onRejected;
var next = state === 'fulfilled' ? callback.resolve : callback.reject;
if (!cb) {
next(value);
return;
}
try {
var ret = cb(value);
next(ret);
} catch (e) {
callback.reject(e);
}
}
function resolve(newValue) {
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then;
if (typeof then === 'function') {
then.call(newValue, resolve, reject);
return;
}
}
state = 'fulfilled';
value = newValue;
setTimeout(function() {
callbacks.forEach(function(callback) {
handle(callback);
});
}, 0);
}
function reject(reason) {
state = 'rejected';
value = reason;
setTimeout(function() {
callbacks.forEach(function(callback) {
handle(callback);
});
}, 0);
}
fn(resolve, reject);
}
```
阅读全文