promise v1.0版本

Tra發表於2018-12-29

實現一個簡單的初始版本

function PromiseA(executor){ 
this.status = 'pending' // 成功value this.value = undefined;
// 失敗reason this.reason = undefined;
// 成功監聽陣列 this.succArr = [];
// 失敗監聽陣列 this.errArr = [];
var that = this;
function resolve(value){
if(that.status === 'pending'){
that.status = 'resolved';
that.value = value;
that.succArr.forEach(function (item) {
item(that.value)
})
}
} function reject(reason) {
if(that.status === 'pending'){
that.status = 'rejected';
that.reason = reason;
that.errArr.forEach(function (item) {
item(that.reason)
})
}
} try {
executor(resolve,reject)
}catch (e) {
reject(e)
}
}PromiseA.prototype = {
constructor:PromiseA, then:function (succFn,errFn) {
var that = this;
if(this.status === 'pending'){
this.succArr.push(function () {
succFn(that.value);

});
this.errArr.push(function () {
errFn(that.reason);

})
} /* * 為什麼還要對status === 'resolved''rejected'做相關處理呢? * 原因:如果promise內部是非同步函式,不做相關處理也是可以的,但是對於內部是同步程式碼時,當執行resolve時,sussArr還未push到then內部函式,導致無法執行then內部函式 * * */ if(this.status === 'resolved'){
succFn(that.value)
} if(this.status === 'rejected'){
errFn(that.reason)
} return this;

}
}/** version:1.0* 描述:1.0版本其實已經簡單的說明了promise的工作流程,說白了promise就是將then內部函式push進 內部陣列 ,當非同步函式執行完畢時,對then內部函式一次執行* 類似以下程式碼* var arr = [];
* $.ajax({* type:'',* url:'',* success:function(res){* arr.forEach(function(item){* item(res)*
})**
}**
})* arr.push(then內部函式)** 未解決的問題:* 1.then的返回其實是一個新的promise,並非當前this* 2.then內部函式均是非同步呼叫* 比如:以原生Promise做demo* console.log('start')* new Promise(function (reslove,reject) {
console.log(1) reslove('2222')
}).then(function (res) {
console.log(res)
},function (err) {
console.log(err)
}) console.log('end') 列印結果為: start 1 end 2222 如果以我們寫的程式碼執行: 列印結果為: start 1 2222 end v2.0解決以上問題* */複製程式碼

來源:https://juejin.im/post/5c27130f6fb9a049ef26a936

相關文章