简单手写js实现promise
时间: 2024-11-24 22:16:47 浏览: 54
在JavaScript中,Promise是一种处理异步操作的技术,它使得我们可以更方便地编写非阻塞的、链式调用的代码。下面是一个简单的手动实现Promise的例子:
```javascript
// 定义Promise构造函数
function Promise(executor) {
// 将executor函数封装到resolve和reject函数中
var resolve = function(value) {
if (this.status === 'fulfilled' || this.status === 'rejected') {
throw new Error('Promise already settled');
}
this.value = value;
this.status = 'fulfilled';
this.onFulfilled.forEach(function(onFulfillment) {
try {
onFulfillment(value);
} catch(e) {
this.reject(e);
}
}, this);
};
var reject = function(reason) {
if (this.status === 'fulfilled' || this.status === 'rejected') {
throw new Error('Promise already settled');
}
this.reason = reason;
this.status = 'rejected';
this.onerror.forEach(function(onError) {
onError(reason);
}, this);
};
// 初始化状态和回调队列
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
// 执行 executor 函数并返回
executor(resolve, reject);
}
// 实现基本的方法 .then() 和 .catch()
Promise.prototype.then = function(onFulfillment, onRejected) {
var promise = new Promise(function(resolve, reject) {
this.onFulfilled = onFulfillment ? [onFulfillment] : [];
this.onerror = onRejected ? [onRejected] : [];
resolve(this.value);
});
if (this.status === 'rejected') {
promise.reject(this.reason);
}
return promise;
};
Promise.prototype.catch = function(onRejected) {
return this.then(null, onRejected);
};
// 使用示例
var myPromise = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('Task completed successfully!');
}, 2000);
});
myPromise
.then(function(result) {
console.log(result); // 输出 "Task completed successfully!" after 2 seconds
})
.catch(function(error) {
console.error(error);
});
```
阅读全文
相关推荐

















