Web dev learning notes and reviews. Sharing my discovery of web tech and open source.
© 2017 | Te-Chi's Dev Note | All rights reserved.
第一次接觸 Promise 的時候是在使用 AngularJS 提供的$http
,它是一個基於XMLHttpRequest
的包裝, 回傳的物件是符合Promise/A+ 的 Promise,因此要理解 Promise 的特性與表現, 才能夠正確的實作網頁應用中的非同步操作與使用者介面變化流程。
然而在面對多個具有相依性的非同步操作,程式碼結構會變得複雜難以維護(波動拳式回呼)。 因此,希望藉著這個機會好好檢視MDN 文件 並學習如何撰寫風格良好的 Promise 程式碼。
myPromise.then(onFulfilled, onRejected)
myPromise
狀態onFulfilled
onRejected
myPromise
提供的訊息並處理,舉例來說myPromise
成功的話寫onFulfilled(val)
處理執行結果myPromise
失敗寫onRejected(reason)
印出失敗原因myPromise.then()
必定會回傳一個 Promise 給你接著用,不論該 Callback 的結果是成功還是失敗.then()
回傳什麼狀態的 Promise?onFulfilled
還是onRejected
),或是最後回傳了另一個做了結果失敗的 Promise (rejected) ,.then()
就會回傳一個狀態為 rejected 的 PromiseonFulfilled
還是onRejected
)回傳了任何值(包含 undefined),或是最後回傳了另一個做了結果成功的 Promise (fulfilled).then()
就會回傳一個狀態為 fulfilled 的 Promise.then()
回傳什麼樣的 Promise 要等 Callback 的結果才會知道.then(...)
可以串聯接著用,像是鎖鏈beGoodKid.then(beGoodStudent,...).then(workSuccess,...)
onFulfilled
函式回傳一個 Promise.then()
在內部的 Callback 如果回傳了 rejected Promise,那.then()
最後就會回傳該 rejected Promise.then()
根據上一個 Promise 的狀態來做對應處理.then()
要提供onRejected
,才可以處理前面產生的 rejected 的 PromisemyPromise.then().then()
裏面都要寫一個onRejected
實在是不好維護onRejected
的話會怎樣?myPromise.then(onFulfilled)
myPromise
最後 fulfilled 的話就照原先,執行onFulfilled
myPromise
最後 rejected 的話.then()
就會回傳原本就是 rejected 的myPromise
onRejected
處理先前任一 Promise 所產生的失敗結果myPromise.catch(onRejected)
beGoodKid().then(()=>{returnbeGoodStudent()// it's async}).then(()=>{returnworkSuccess()// it's async}).catch()=>{console.warn('your parents are angry')}
按:只要一件事情沒做好,後面就沒機會了。
一個很喜歡的簡潔範例,以 Promise 結合 array 的reduce()
,依序於 Atom 編輯器開啟多個檔案
constpath=require('path');constos=require('os');constpaths=['file.one','file.two','file.three'];paths.reduce((cur,nextPath)=>{returncur.then(()=>{// return .then() for next promisereturnatom.workspace.open(nextPath);// return an open job as a promise});},Promise.resolve('start'));// init promise
.then(onFulfilled, onRejected)
讓 Promise 的狀態變化會觸發對應的 Callback.then()
和.catch()
必定回傳一個 Promise ,這個特性讓你可以把 Promise 串成鎖鏈,有相依性的執行數個非同步工作