上一篇介绍了
promise的概念和方法01
如何使用promise实现ajax02
这一篇介绍使用纯原生js实现promise
class NewPromise {
constructor(executor) {
if (typeof executor !== 'function') {
throw new Error('Executor must be a function');
}
this.state = 'pending';
this.statesSave = [];
const resolve = res => {
if (this.state !== 'pending') {
return;
}
this.state = 'resolved';
this.internalValue = res;
for (const { onResolved } of this.statesSave) {
onResolved(res);
}
};
const reject = err => {
if (this.state !== 'pending') {
return;
}
this.state = 'rejected';
this.internalValue = err;
for (const { onRejected } of this.statesSave) {
onRejected(err);
}
};
try {
executor(resolve, reject);
} catch (err) {
reject(err);
}
}
then(onResolved, onRejected) {
if (this.state === 'resolved') {
onResolved(this.internalValue);
} else if (this.$state === 'rejected') {
onRejected(this.internalValue);
}
else {
this.statesSave.push({ onResolved, onRejected });
}
}
}
let p = new NewPromise(resolve => {
// resolve('Hello');
setTimeout(() => resolve('Hello'), 3000);
});
p.then(res => console.log(res));//Hello
over~ 有问题留言