为什么 super 中能接收到 resolve 和 reject?

0 阅读1分钟

在这段代码中:

        
class NotifiablePromise extends Promise {
  constructor(executor) {
    let notifyFn;

    super((resolve, reject) => {
      executor(resolve, reject, (progress) => {
        if (notifyFn) notifyFn(progress);
      });
    });

    this._listeners = [];
    notifyFn = (progress) => {
      this._listeners.forEach(fn => fn(progress));
    };
  }
}
        
      

因为 NotifiablePromise 继承自 Promise,所以构造函数里的 super(...) 表示调用父类 Promise 的构造函数。

这里传给 super 的是一个函数:

        
(resolve, reject) => {
  // ...
}
        
      

它就是传给 Promise 的 executor。Promise 构造函数会创建 resolve、reject 两个函数,并立即调用 executor:

        
executor(resolve, reject);
        
      

因此,这里的 resolve 和 reject 是由 Promise 构造函数提供的参数。子类通过包装函数接收到它们,再传给创建 NotifiablePromise 时传入的原始 executor:

        
executor(resolve, reject, notify);
        
      

执行过程可以简化为:

        
super(wrapper)
  ↓
Promise 构造函数调用 wrapper(resolve, reject)
  ↓
wrapper 将 resolve、reject 转交给原始 executor
        
      

例如:

        
const promise = new NotifiablePromise((resolve, reject, notify) => {
  setTimeout(() => {
    notify(50);
    resolve("完成");
  }, 1000);
});
        
      

这里,原始 executor 中的 resolve 和 reject,就是 Promise 父类创建并传下来的函数;notify 则是子类额外添加的第三个参数,用来发送进度通知。

需要注意,Promise 会同步调用传入的 executor。因此,原始 executor 如果在同步执行期间调用 notify,此时 notifyFn 可能还未赋值,通知会被忽略。通常在定时器、网络请求等异步任务中调用 notify,则可以避开这个问题。

总结来说:super 调用的是父类 Promise 的构造函数;Promise 构造函数再把 resolve 和 reject 传给它收到的 executor。