class Promise {
// @param {function} eg: (resolve, reject) => { resolve() }
constructor (exector) {
this._queue = [] // 存储通过 then 方法传入的的函数
this._exector = exector // 调用 then 方法时执行该函数
}
then (onResolved, onRejected) {
this._queue.push([onResolved, onRejected])
this._exector(this._resolve.bind(this), this._reject.bind(this))
}
_resolve (data) {
this._next(0, data)
}
_reject (reason) {
this._next(1, reason)
}
// state 0 代表 resolve, 1 代表 reject
_next (state, val) {
let arr = this._queue.shift()
if (arr) {
arr[state](val)
}
}
}