Promise
內部源碼//定義新的Promise類 class LxPromise{ constructor(fn) { //將成功的事件函數集成在successList數組裏 this.successList = []; //這裏將全部的失敗函數集成到failList裏 this.failList = [] //pending,fullfilled,rejected this.state = "pending" //傳入的函數對象,(異步操做的函數內容) //而且調用resolveFn()和rejectFn()方法 //將resolveFn/rejectFn和傳入的func綁定 //resolve() => resolveFn() //reject() => rejectFn() fn(this.resolveFn.bind(this),this.rejectFn.bind(this)) } //定義then方法,把傳入的func壓入list數組 then(successFn,failFn){ if(typeof successFn=='function'){ this.successList.push(successFn) } if(typeof failFn=='function'){ this.failList.push(failFn) } } catch(failFn){ if(typeof failFn=='function'){ this.failList.push(failFn) } } //聲明resolve實現函數 resolveFn(res){ this.state = "fullfilled" this.successList.forEach(function(item,index){ //將成功的事件循環調用 item(res) }) } //聲明reject實現函數 rejectFn(res){ this.state = 'rejected' //註冊到的失敗全部事件進行調用 this.failList.forEach(function(item,index){ item(res) }) throw Error(res); } } //******************LxPromise()構造結束*****************
//參數 var fn = function(resolve,reject){ setTimeout(function(){ if(true){ //函數調用 resolve("老陳promise成功") }else{ //函數調用 reject("老陳promise失敗") } },1000) } //建立實例對象 var p1 = new LxPromise(fn); //函數聲明,和函數的具體操做 p1.then(function(res){ document.body.style.background = "greenyellow" console.log("這是成功作的事情") console.log(res) }) p1.catch(function(res){ document.body.style.background = "pink" console.log("這是失敗作的事情") console.log(res) })
ok~實現!可能還不是很完整,不過旨在學習認清promise的實現和運做過程。數組