手写Promise

class Promise {
 constructor(executor) {
 if (typeof executor !== 'function') {
  throw new Error('Executor must be a function');
 }
 
 this.state = 'PENDING';
 this.chained = []; //// chained用来储存promise执行完成以后,需要被依次调用的一系列函数
 const resolve = res => {
  if (this.state !== 'PENDING') {
  return;
  }
 
  this.state = 'FULFILLED';
  this.value = res;
  for (const { onFulfilled } of this.chained) {
  onFulfilled(res);
  }
 };
 const reject = err => {
  if (this.state !== 'PENDING') {
  return;
  }
  this.state = 'REJECTED';
  this.value = err;
  for (const { onRejected } of this.chained) {
  onRejected(err);
  }
 };
 
 try {
  executor(resolve, reject);
 } catch (err) {
  reject(err);
 }
 }
  
 then(onFulfilled, onRejected) {
 if (this.state === 'FULFILLED') {
  onFulfilled(this.value);
 } else if (this.state === 'REJECTED') {
  onRejected(this.value);
 } else {
  this.chained.push({ onFulfilled, onRejected });
 }
 }
}

你可能感兴趣的:(手写Promise)