promise源码实现
时间: 2023-10-12 22:03:52 浏览: 116
Promise的源码实现比较复杂,这里我给你一个简化版的Promise源码示例,以帮助你理解其基本原理:
```javascript
// Promise构造函数
function Promise(executor) {
var self = this;
self.value = null; // Promise的值
self.status = 'pending'; // Promise的状态
self.onResolvedCallbacks = []; // 存储成功回调函数的数组
self.onRejectedCallbacks = []; // 存储失败回调函数的数组
function resolve(value) {
if (self.status === 'pending') {
self.status = 'resolved';
self.value = value;
self.onResolvedCallbacks.forEach(function (callback) {
callback(value);
});
}
}
function reject(reason) {
if (self.status === 'pending') {
self.status = 'rejected';
self.value = reason;
self.onRejectedCallbacks.forEach(function (callback) {
callback(reason);
});
}
}
try {
executor(resolve, reject);
} catch (e) {
reject(e);
}
}
// then方法
Promise.prototype.then = function (onResolved, onRejected) {
var self = this;
var promise2;
onResolved = typeof onResolved === 'function' ? onResolved : function (value) { return value; };
onRejected = typeof onRejected === 'function' ? onRejected : function (reason) { throw reason; };
if (self.status === 'resolved') {
return promise2 = new Promise(function (resolve, reject) {
try {
var x = onResolved(self.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (self.status === 'rejected') {
return promise2 = new Promise(function (resolve, reject) {
try {
var x = onRejected(self.value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
}
if (self.status === 'pending') {
return promise2 = new Promise(function (resolve, reject) {
self.onResolvedCallbacks.push(function (value) {
try {
var x = onResolved(value);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
self.onRejectedCallbacks.push(function (reason) {
try {
var x = onRejected(reason);
resolvePromise(promise2, x, resolve, reject);
} catch (e) {
reject(e);
}
});
});
}
};
// 解析Promise的状态
function resolvePromise(promise, x, resolve, reject) {
var then;
var thenCalledOrThrow = false;
if (promise === x) {
return reject(new TypeError('Chaining cycle detected for promise!'));
}
if (x instanceof Promise) {
if (x.status === 'pending') {
x.then(function (value) {
resolvePromise(promise, value, resolve, reject);
}, reject);
} else {
x.then(resolve, reject);
}
return;
}
if ((x !== null) && ((typeof x === 'object') || (typeof x === 'function'))) {
try {
then = x.then;
if (typeof then === 'function') {
then.call(x, function rs(y) {
if (thenCalledOrThrow) return;
thenCalledOrThrow = true;
return resolvePromise(promise, y, resolve, reject);
}, function rj(r) {
if (thenCalledOrThrow) return;
thenCalledOrThrow = true;
return reject(r);
});
} else {
resolve(x);
}
} catch (e) {
if (thenCalledOrThrow) return;
thenCalledOrThrow = true;
return reject(e);
}
} else {
resolve(x);
}
}
```
这只是一个简化版的Promise源码实现,真正的Promise实现要考虑更多的细节和边界情况。希望这个示例能帮助你更好地理解Promise的工作原理。
阅读全文