怎么自己实现一个promise
时间: 2023-10-09 18:10:31 浏览: 150
实现Promise的基本思路如下:
1. 创建一个Promise类,它具有resolve、reject、then、catch等方法
2. 在Promise类中定义一个状态变量,可以是pending、fulfilled、rejected中的一种
3. 定义一个存储回调函数的数组,当Promise状态发生改变时,会执行这些回调函数
4. 在resolve和reject方法中,改变Promise的状态,并执行相应的回调函数
5. 在then和catch方法中,将回调函数添加到数组中,如果Promise已经完成,则立即执行回调函数,否则等待Promise的状态改变后再执行回调函数
下面是一个简单的Promise实现示例:
```javascript
class MyPromise {
constructor(executor) {
this.status = 'pending'; // 初始状态为pending
this.value = null; // 成功时的返回值
this.reason = null; // 失败时的原因
this.handlers = []; // 存储回调函数的数组
executor(this.resolve.bind(this), this.reject.bind(this));
}
resolve(value) {
if (this.status === 'pending') {
this.status = 'fulfilled'; // 改变状态为fulfilled
this.value = value; // 保存成功时的返回值
this.handlers.forEach(handler => handler.onFulfilled(value)); // 执行成功的回调函数
}
}
reject(reason) {
if (this.status === 'pending') {
this.status = 'rejected'; // 改变状态为rejected
this.reason = reason; // 保存失败时的原因
this.handlers.forEach(handler => handler.onRejected(reason)); // 执行失败的回调函数
}
}
then(onFulfilled, onRejected) {
if (typeof onFulfilled !== 'function') {
onFulfilled = value => value;
}
if (typeof onRejected !== 'function') {
onRejected = reason => { throw reason };
}
return new MyPromise((resolve, reject) => {
if (this.status === 'pending') {
this.handlers.push({
onFulfilled: value => {
try {
const result = onFulfilled(value);
if (result instanceof MyPromise) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
reject(error);
}
},
onRejected: reason => {
try {
const result = onRejected(reason);
if (result instanceof MyPromise) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
reject(error);
}
}
});
} else if (this.status === 'fulfilled') {
setTimeout(() => {
try {
const result = onFulfilled(this.value);
if (result instanceof MyPromise) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
reject(error);
}
}, 0);
} else if (this.status === 'rejected') {
setTimeout(() => {
try {
const result = onRejected(this.reason);
if (result instanceof MyPromise) {
result.then(resolve, reject);
} else {
resolve(result);
}
} catch (error) {
reject(error);
}
}, 0);
}
});
}
catch(onRejected) {
return this.then(null, onRejected);
}
}
```
使用示例:
```javascript
const promise = new MyPromise((resolve, reject) => {
setTimeout(() => {
resolve('hello world');
}, 1000);
});
promise.then(value => {
console.log(value); // 输出'hello world'
}).catch(reason => {
console.error(reason);
});
```
阅读全文