function Promise(executor){
//在內部中定義一個狀態,當前promise狀態
let self = this
self.value = undefined
self.reason = undefined
self.status = 'pending' //默認promise狀態是padding
function resolve(value){
if(self.status === 'pending'){
self.value = value
self.status = 'resolved'; //成功了
}
}
function reject(reason){
if(self.status === 'pending'){
self.reason = reason
self.status = 'rejected' //失敗態
}
}
executor(resolve,reject)
}
Promise.prototype.then = function (onFulfilled,onRejected){
let self = this
if(self.status === 'resolved') {
onFulfilled(self.value)
}
if(self.status === 'rejected') {
onRejected(self.reason)
}
}
module.exports = Promise
複製代碼