|
導讀網頁的本質就是超級文本標記語言,通過結合使用其他的Web技術(如:腳本語言、公共網關接口、組件等),可以創造出功能強大的網頁。因而,超級文本標記語言是萬維網(Web)編程的基礎,也就是說萬維網是建立... 網頁的本質就是超級文本標記語言,通過結合使用其他的Web技術(如:腳本語言、公共網關接口、組件等),可以創造出功能強大的網頁。因而,超級文本標記語言是萬維網(Web)編程的基礎,也就是說萬維網是建立在超文本基礎之上的。超級文本標記語言之所以稱為超文本標記語言,是因為文本中包含了所謂“超級鏈接”點。 本篇文章給大家帶來的內容是關于Promise實現思路的深入分析(代碼示例),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。Promise實現思路的個人理解 我一直覺得Promise雖然方便,但是它的寫法很怪,無法理解實現Promise的人是如何思考的。 不過最近我對于實現Promise的思考過程的有了一點點個人理解,特此記下。 感覺這篇文章我還是沒有把思路說清楚,時間緊張,就當做一次記錄,回頭我要把這個過程在表達的在清楚一點。 用例 var p1 = new Promise2( ( resolve, reject ) => {
setTimeout( () => {
resolve( 'hello' )
}, 1000 )
} )
p1.then( res => {
console.log( res + 'world' )
return res + 'world'
} )
.then( res => {
console.log( res + 'ziwei' )
return res + 'ziwei'
} )我覺得實現一個函數跟封裝組件類似,首先從以下幾點考慮:
那么結合例子,和這幾個問題,我們得到
先實現一個Promise(未實現then的鏈式調用)
class Promise2 {
constructor( fn ) {
this.successFnArray = [] // 用來緩存successFn和errorFn
this.errorFnArray = []
this.state = 'pendding'
const resolve = ( res ) => { // resolve就做2件事情 1: 修改狀態 2:調用successFn
this.state = 'fulfilled'
this.value = res // this.value用來緩存data數據或者error
this.successFnArray.forEach( successFn => {
successFn( res )
} )
}
const reject = ( err ) => {
this.state = 'rejected'
this.value = err
this.errorFnArray.forEach( errorFn => {
errorFn( res )
} )
}
fn( resolve, reject ) // 先調用fn再說
}
then( successFn, errorFn ) {
switch ( this.state ) {
case 'fulfilled':
successFn( this.value ) // 如果調用了resolve,狀態就成了fulfilled,就會執行successFn
break
case 'rejected':
errorFn( this.value )
break
case 'pendding':
this.successFnArray.push( successFn ) // 如果還沒調用resolve,狀態就是pendding,就先把這些異步函數緩存起來。將來resole時調用
this.errorFnArray.push( errorFn )
}
}
}
var p1 = new Promise2( ( resolve, reject ) => {
setTimeout( () => {
resolve( 'hello' )
}, 1000 )
} )
p1.then( res => {
console.log( res + 'world' )
return res + 'world'
} )實現then鏈式調用 then的實現,和JQ的鏈式調用不同,JQ是每次調用方法后,把this返回 而Promise規范要求,每次都要返回新的Promise對象 所以只需要把then方法修改一下。 這部分可能會迷惑,但是我想先說一下這里做了哪些事情,其實變化不大 之前的then做了哪些事情?
鏈式then有哪些改動?
而是調用_successFn,而這個函數內部本質上還是調用successFn(),但同時把調用的返回值作為了resolve的參數,調用了resolve() 因為當successFn被調用,得到返回值時,就表示這個函數執行完了, 就需要執行下一個異步函數了,這樣下一個異步函數也會把successFn(res)的return值作為參數 then( successFn, errorFn ) {
return new Promise2( ( resolve, reject ) => {
const _successFn = res => {
resolve(successFn(res))
}
const _errorFn = err => {
reject(errorFn(err))
}
switch ( this.state ) {
case 'fulfilled':
_successFn( this.value )
break
case 'rejected':
_errorFn( this.value )
break
case 'pendding':
this.successFnArray.push( _successFn )
this.errorFnArray.push( _errorFn )
}
} )
}以上就是Promise實現思路的深入分析(代碼示例)的詳細內容,更多請關注php中文網其它相關文章! 網站建設是一個廣義的術語,涵蓋了許多不同的技能和學科中所使用的生產和維護的網站。 |
溫馨提示:喜歡本站的話,請收藏一下本站!