class Promise {constructor(resolver) {this[PROMISE_ID] = nextId()this._result = this._state = undefinedthis._subscribers = []if (noop !== resolver) {typeof resolver !== 'function' && needsResolver()this instanceof Promise ? initializePromise(this, resolver) : needsNew()}}}
首先我们的 Promise 是通过 ES6 Class 类进行定义的。在构造函数中接收一个参数 resolver,也就是我们用户传入进来的接收器,这里的形式就相当于回调函数,接收了两个参数,最后是由 Promise 进行调用。
const p1 = new Promise((resolve, reject) => {resolve(true)})
在定义 Promise 构造函数中,主要核心的部分就是定义了一个状态 _state,表示当前 promise 的状态是成功、失败还是等待中。
this._state = undefined
代码的最后还有一个逻辑判断,如果用户传入了 resolver 才会继续执行下方的代码,并且 resolver 必须是一个函数,Promise 必须通过 new 关键字进行实例化,否则会抛出相应的错误信息。
if (noop !== resolver) {typeof resolver !== 'function' && needsResolver()this instanceof Promise ? initializePromise(this, resolver) : needsNew()}
通过验证后,最终调用 initializePromise 初始化一个 Promise。
