day200-简单实现Promise(2)

要点

  1. 修改promise状态

代码

/** 构造函数 - 雏形 */
function Promise (fn) {
let self = this
self.status = 'pending'
self.data = undefined

self.onFulfilledCallback = [] // resolve 回调函数集合
self.onRejectedCallback = [] // reject 回调函数集合

function resolve (value) {
if (self.status === 'pending') {
self.status = 'resolved'
self.data = value
for (var i = 0; i < self.onFulfilledCallback.length; i++) {
self.onFulfilledCallback[i](value)
}
}
}

function reject (reason) {
if (self.status === 'pending') {
self.status = 'rejected'
self.data = reason
for (var i = 0; i < self.onRejectedCallback.length; i++) {
self.onRejectedCallback[i](reason)
}
}
}

try {
fn (resolve, reject) // 执行传入的函数,传入
} catch (error) {
reject(error)
}
}
文章作者: lmislm
文章链接: http://lmislm.com/2019/08/01/2019-08-01/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 LMISLMのBlog