一个简单的Promise
前置文章这一次,彻底弄懂 Promise 原理
使用class实现简单的Promise
class Promise {
constructor(callback) {
this.state = 'pending';
this.value = null;
this.error = null;
this.successCallback = [];
this.errorCallback = [];
this.resolve = this.resolve.bind(this);
this.reject = this.reject.bind(this);
callback(this.resolve, this.reject);
}
resolve(value) {
if (this.state === 'pending') {
this.state = 'resolved';
this.value = value;
setTimeout(() => {
this.successCallback.forEach((callback) => {
callback(this.value);
});
}, 0);
}
}
reject(error) {
if (this.state === 'pending') {
this.error = error;
this.state = 'resolved';
setTimeout(() => {
this.errorCallback.forEach((callback) => {
callback(this.error);
});
}, 0);
}
}
then(success, fail) {
this.successCallback.push(success);
this.errorCallback.push(fail);
return this;
}
}
test case
new Promise((resolve, reject) => {
resolve({name:'zs',age:12});
reject({errMsg:'我错了'});
})
.then(
(value) => {
console.log(value);
},
(error) => {
console.log(error);
}
)
.then(
(value) => {
console.log('第二个', value);
},
(error) => {
console.log(error);
}
);