原生Promise解析
簡介
promise是異步編程的一種解決方案,比傳統的解決方案--回調函數和事件--更合理和強大。
promise簡單說就是一個容器,里面保存著某個未來才會結束的事件(通常是一個異步操作)的結果,從語法上來說,Promise是一個對象,從它可以獲取異步操作的消息,Promise提供統一的API,各種異步操作都可以用同樣的方法進行處理
特點
對象的狀態不受外界影響,Promise對象代表一個異步操作,有三種狀態:Pendding、fulfilled、rejected。只有異步操作的結果,可以決定當前是哪一種狀態,其他操作都無法改變這個狀態。
一旦狀態改變,就不會在變,任何時候都可以得到這個結果,只有兩種可能:從Pendding變為fulfilled和從Pendding變為rejected。只要這兩種情況發生,狀態就凝固了,會一直保持這個結果,這時就稱為resolved。
利用es6進行Promise封裝
處理同步任務
原生方法調用方式
new Promise((resolve,reject)=>{ resolve(1) }).then(res=>{ console.log(res) //1 })同步封裝思考
1.由調用方式可見Promise是一個類
2.它接收一個回調函數,這個回調函數接受resolve和reject方法作為參數
3.當狀態改變后執行then方法,并將resolve或reject的結果作為then方法接受回調函數的參數
class Mypromise{ constructor(callback){ this.status='pendding' //成功結果 this.s_res = null // 失敗結果 this.f_res = null callback((arg)=>{ // 使用箭頭函數this不會丟失 // 改變狀態為成功 this.status = 'fulfilled' this.s_res = arg },(arg)=>{ // 改變狀態為失敗 this.status = 'rejected' this.f_res = arg }) } then(onresolve,onreject){ if(this.status === 'fulfilled'){ // 當狀態為成功時 onresolve(this.s_res) }else if(this.status === 'rejected'){ // 當狀態為失敗時 onreject(this.f_res) } } }處理異步任務
原生調用方式
new Promise((resolve,reject)=>{ setTimeOut(()=>{ resolve(1) },1000) }).then(res=>{ console.log(res) })異步封裝思考
1.根據js執行機制,setTimeOut屬于宏任務,then回調函數屬于微任務,當主線程執行完成后,會從異步隊列中取出本次的微任務先執行。
2.也就是說,then方法執行時,狀態還沒有改變,所有我們需要將then方法執行的回調保存起來,等到異步代碼執行完成后,在統一執行then方法的回調函數
class Mypromise{ constructor(callback){ this.status='pendding' //成功結果 this.s_res = null // 失敗結果 this.f_res = null this.query = [] // ++ callback((arg)=>{ // 使用箭頭函數this不會丟失 // 改變狀態為成功 this.status = 'fulfilled' this.s_res = arg // 當狀態改變后,統一執行then方法的回調 this.query.forEach(item=>{ item.resolve(arg) }) },(arg)=>{ // 改變狀態為失敗 this.status = 'rejected' this.f_res = arg // 當狀態改變后,統一執行then方法的回調 this.query.forEach(item=>{ item.reject(arg) }) }) } then(onresolve,onreject){ if(this.status === 'fulfilled'){ // 當狀態為成功時 onresolve(this.s_res) }else if(this.status === 'rejected'){ // 當狀態為失敗時 onreject(this.f_res) }else{ // ++ 狀態沒有改變 this.query.push({ // 保存回調函數到隊列中 resolve:onresolve, reject:onreject }) } } }
新聞熱點
疑難解答
圖片精選