class Promise{
????constructor(excutorCallBack){
????????this.status = 'pending'
????????this.value = undefined;
????????this.fulfilledAry = []; //管控,必須得then執(zhí)行后才能執(zhí)行resolveFn方法,成功要做的方法
????????this.rejectedAry = []; //失敗要做的方法
????????// => 執(zhí)行EXCUTOP
????????let resolveFn = (result) =>{
????????????let timer = setTimeout(()=>{
????????????????if(this.status !== 'pending') return;
????????????????clearTimeout(timer)
????????????????this.status = 'fulfilled';
????????????????this.value = result;
????????????????this.fulfilledAry.forEach(item=>item(this.value))
????????????},0)
????????};
????????let rejectFn = (reason) =>{
????????????let timer = setTimeout(()=>{
????????????????clearTimeout(timer)
????????????????if(this.status !== 'pending') return;
????????????????this.status = 'rejected';
????????????????this.value = reason;
????????????????this.rejectedAry.forEach((item)=>item(this.value))
????????????},0)
????????}
????????// => 執(zhí)行EXCUTOP(異常捕獲)
????????try{
????????????excutorCallBack(resolveFn,rejectFn);
????????} catch (err){
????????????// 有異常信息按照rejected狀態(tài)信息處理
????????????rejectFn(err);
????????}
????}
????then (fulfilledCallBack,rejectedCallBack) {
????????// fulfilledCallBack不傳遞的情況
????????typeof fulfilledCallBack !== 'function'? fulfilledCallBack = result =>{
????????????return result
????????} : null;
????????typeof rejectedCallBack !== 'function'? rejectedCallBack = reason =>{
????????????throw new Error(reason.message)
????????} : null
????????// 返回一個新的Promise實例
????????return new Promise((resolve,reject)=>{
????????????this.fulfilledAry.push(()=>{
????????????????try {
????????????????????let x = fulfilledCallBack(this.value);
????????????????????if(x instanceof Promise){
????????????????????????x.then(resolve,reject);
????????????????????????return;
????????????????????}
????????????????????resolve(x);
????????????????}catch(err){
????????????????????reject(err)
????????????????}
????????????});
????????????this.rejectedAry.push(()=>{
????????????????try{
????????????????????let x = rejectedCallBack(this.value);
????????????????????if(x instanceof Promise){
????????????????????????x.then(resolve,reject);
????????????????????????return;
????????????????????}
????????????????????resolve(x)
????????????????}catch(err){
????????????????????reject(x)
????????????????}
????????????})
????????});
????}
????catch(rejectedCallBack){
????????return this.then(null,rejectedCallBack)
????}
}
module.exports = Promise;
