initializePromise
function initializePromise(promise, resolver) {try {resolver(function resolvePromise(value) {resolve(promise, value)},function rejectPromise(reason) {reject(promise, reason)})} catch (e) {reject(promise, e)}}
函数 initializePromise 接收了两个参数,一个是 Promise 类,一个是用户传入的回调函数 resolver 。函数中调用了用户传入的 resolver ,并且传又传回了两个参数,这两个参数又是一个回调函数,由用户进行主动触发。一个是 resolvePromise,另外一个是 rejectPromise 主要是用来更改当前 promise 的状态。
resolve
function resolve(promise, value) {if (promise === value) {reject(promise, selfFulfillment())} else if (objectOrFunction(value)) {let thentry {then = value.then} catch (error) {reject(promise, error)return}handleMaybeThenable(promise, value, then)} else {fulfill(promise, value)}}
resolve 代码中主要核心的就是 fulfill 函数的调用,主要用来更改当前 promise 的状态和返回值。
fulfill
function fulfill(promise, value) {if (promise._state !== PENDING) {return}promise._result = valuepromise._state = FULFILLEDif (promise._subscribers.length !== 0) {asap(publish, promise)}}
fulfill 主要是用来修改当前 promise 返回的值以及 promise 当前的状态。
