手写promise对象
时间: 2023-08-25 15:19:06 浏览: 94
回答: 手写Promise对象的代码可以参考以下示例:
```javascript
function MyPromise(fn) {
this.PromiseState = "pending";
this.PromiseResult = undefined;
this.thenCallback = undefined;
this.catchCallback = undefined;
var resolve = (value) => {
if (this.PromiseState === "pending") {
this.PromiseState = "fulfilled";
this.PromiseResult = value;
if (this.thenCallback) {
this.thenCallback(value);
}
}
};
var reject = (errValue) => {
if (this.PromiseState === "pending") {
this.PromiseState = "rejected";
this.PromiseResult = errValue;
setTimeout(() => {
if (this.catchCallback) {
this.catchCallback(errValue);
} else if (this.thenCallback) {
this.thenCallback(errValue);
} else {
throw "catch is not defined!!!!";
}
});
}
};
if (fn) {
fn(resolve, reject);
}
}
MyPromise.prototype.then = function (onFulfilled) {
this.thenCallback = onFulfilled;
return this;
};
MyPromise.prototype.catch = function (onRejected) {
this.catchCallback = onRejected;
return this;
};
new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve("成功回调");
// reject("失败的回调");
}, 1000);
}).then((value) => {
console.log(value);
}).catch((reason) => {
console.log(reason);
});
```
这段代码实现了一个简单的Promise对象,包含了`resolve`和`reject`方法,以及`then`和`catch`方法。当调用`resolve`方法时,会将Promise的状态设置为成功,并执行`then`回调函数;当调用`reject`方法时,会将Promise的状态设置为失败,并执行`catch`回调函数。在上述示例中,通过`setTimeout`模拟了异步操作,以演示Promise的使用。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [教你如何手写一个Promise](https://blog.csdn.net/ose_huang/article/details/123141668)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *3* [【手写Promise】](https://blog.csdn.net/weixin_49487698/article/details/124793415)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文