手写promise函数
时间: 2023-09-12 16:02:46 浏览: 89
好的,关于手写实现Promise函数,其实Promise是一种异步编程的解决方案,它的本质是对回调函数的封装,可以更加优雅和简洁地处理异步操作。以下是一个简单的手写Promise函数示例:
```javascript
function MyPromise(fn) {
var self = this;
self.status = 'pending';
self.value = null;
self.reason = null;
self.onFulfilledCallbacks = [];
self.onRejectedCallbacks = [];
function resolve(value) {
if (self.status === 'pending') {
self.status = 'fulfilled';
self.value = value;
self.onFulfilledCallbacks.forEach(function(callback) {
callback(self.value);
});
}
}
function reject(reason) {
if (self.status === 'pending') {
self.status = 'rejected';
self.reason = reason;
self.onRejectedCallbacks.forEach(function(callback) {
callback(self.reason);
});
}
}
try {
fn(resolve, reject);
} catch (e) {
reject(e);
}
}
MyPromise.prototype.then = function(onFulfilled, onRejected) {
var self = this;
return new MyPromise(function(resolve, reject) {
if (self.status === 'fulfilled') {
try {
var x = onFulfilled(self.value);
resolve(x);
} catch (e) {
reject(e);
}
} else if (self.status === 'rejected') {
try {
var x = onRejected(self.reason);
resolve(x);
} catch (e) {
reject(e);
}
} else if (self.status === 'pending') {
self.onFulfilledCallbacks.push(function(value) {
try {
var x = onFulfilled(value);
resolve(x);
} catch (e) {
reject(e);
}
});
self.onRejectedCallbacks.push(function(reason) {
try {
var x = onRejected(reason);
resolve(x);
} catch (e) {
reject(e);
}
});
}
});
}
```
以上就是一个简单的手写Promise函数的实现,它是基于回调函数的封装实现的异步编程方案。
阅读全文