Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

怎样手写一个教学版 Promise?

先说出你的答案

定义边界、关键机制、一个反例;P8题再补容量、失败与验证。

查看完整题解

参考回答

直接回答

实现的骨架是状态、兑现值或拒绝原因、等待中的处理函数。构造函数会同步调用执行器。第一次 resolve 或 reject 锁定决议。then 返回一个新对象,处理函数排入微任务,结果或错误传给新对象。

讲清原理

如果处理函数返回另一个可接续对象,即有 then 方法的 thenable,要接上它的结果。读取 then 或调用 then 都可能抛错。自身回环要拒绝,避免链一直等自己。

例子与易错点

下面是教学实现,演示单次决议、异步派发、错误、链式值和 thenable 采纳。标准 Promise 还定义子类构造、宿主拒绝追踪及静态组合方法,项目里直接使用内置 Promise。

class MiniPromise {
  constructor(executor) {
    this.state = 'pending';
    this.result = undefined;
    this.handlers = [];

    let locked = false;
    const resolve = value => {
      if (locked) return;
      locked = true;
      this.adopt(value, new WeakSet());
    };
    const reject = error => {
      if (locked) return;
      locked = true;
      this.settle('rejected', error);
    };

    try {
      executor(resolve, reject);
    } catch (error) {
      reject(error);
    }
  }

  adopt(value, seen) {
    if (value === this) {
      this.settle('rejected', new TypeError('Promise 不能等待自身'));
      return;
    }
    if (value !== null && (typeof value === 'object' || typeof value === 'function')) {
      let then;
      try {
        then = value.then;
      } catch (error) {
        this.settle('rejected', error);
        return;
      }
      if (typeof then === 'function') {
        if (seen.has(value)) {
          this.settle('rejected', new TypeError('检测到 thenable 回环'));
          return;
        }
        seen.add(value);
        queueMicrotask(() => {
          let called = false;
          const ok = next => {
            if (called) return;
            called = true;
            this.adopt(next, seen);
          };
          const fail = error => {
            if (called) return;
            called = true;
            this.settle('rejected', error);
          };
          try {
            Reflect.apply(then, value, [ok, fail]);
          } catch (error) {
            fail(error);
          }
        });
        return;
      }
    }
    this.settle('fulfilled', value);
  }

  settle(state, result) {
    if (this.state !== 'pending') return;
    this.state = state;
    this.result = result;
    const waiting = this.handlers.splice(0);
    for (const handler of waiting) queueMicrotask(handler);
  }

  then(onFulfilled, onRejected) {
    return new MiniPromise((resolve, reject) => {
      const run = () => {
        const fulfilled = this.state === 'fulfilled';
        const handler = fulfilled ? onFulfilled : onRejected;
        if (typeof handler !== 'function') {
          (fulfilled ? resolve : reject)(this.result);
          return;
        }
        try {
          resolve(handler(this.result));
        } catch (error) {
          reject(error);
        }
      };
      if (this.state === 'pending') this.handlers.push(run);
      else queueMicrotask(run);
    });
  }
}

相关题 第 8 题、第 57 题、第 99 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。