# 基礎的 Promise|筆記 by Sz ###### tags: `Sz` `課前` `Vue新手夏令營` - [Vue 新手夏令營 課程頁面](https://hackmd.io/@dbFY0UD9SUeKmNXhWf01ew/BkJoW-hn_/%2FC05go-8iTSS-nrMwKU22kA) - [:sun_with_face:筆記入口](/2JiZbCPdR0G4p5fNycPmTg) 目前為止的程式碼,就像自言自語,都是單方面發出 但如果需要搭配資料庫,就像多了一個對話的對象,除了單方面的講,也要聽,再做反應 promise 就可以讓程式簡潔的做出這樣的一連串行為 ## 結構 這裡有個目前還不懂怎麼建構的 Promise (了解如何運用即可) ``` const promiseSetTimeout = (status) => { // 建立函式,return 是一個 promise return new Promise((resolve, reject) => { // promise 有兩個參數 resolve, reject setTimeout(() => { // 這函式執行完,才會開始判斷非同步的結果 if (status) { // 若判斷成功,執行 resovle resolve('promiseSetTimeout 成功') // resolve 經過神奇的動作後會得到這 string } else { // 若狀態判斷失敗,執行 reject reject('promiseSetTimeout 失敗') } }, 0); }) } ``` ## 流程 1. pending:未確認狀態,這裡會先跑完所有的程式碼 2. setteled:確認狀態 - Fulfilled:進入 resolve (成功) - Rejected:進入 reject (失敗) #### 成功的話 執行 .then ``` .then(onFulfilled) ``` #### 失敗的話 跳過 then 語法,執行 .catch ``` .catch(onRejection) ``` ## 運用 程式碼的成功與否是由 promise 判斷 ### 假設 promise 回傳成功(true) .then() ``` promiseSetTimeout(true); // 假設 promise 回傳成功 .then(res => console.log(res)) // 神奇的 string 會傳入 res 參數 ``` ### 假設 promise 回傳失敗(false) .catch() ``` promiseSetTimeout(false); // 假設 promise 回傳失敗 .catch(err => console.log(err)) // 神奇的 string 會傳入 err 參數 ``` ## 串接 Concatenation 一連串的 promise 來處理 要取得 A 要先取得 B 的資料,要 B 資料要先取得 C 的情形 假設用上面一個語法進行串接 ``` promiseSetTimeout(true); // 假設 promise 回傳成功 .then(res => { console.log(res); promiseSetTimeout(true);} // 串接下一次的 promise ) .then(res => { // return 的 promise 結果成功的話就繼續執行 then console.log(res); promiseSetTimeout(true);} ) ``` ## 在元件中的 promise 運用 很常在 component 中有 method 處理非同步資料 再儲存到 component 中的 data 裡 > 這邊沒有很確定, then 算一個 function 嗎,還是整個 promiseSetTimeOut 算一個 function ``` const component = { data: {}, // 儲存非同步資料結果 init() { console.log(this) // 這個是下方箭頭函式的外層 this promiseSetTimeOut(true) // 放入一個 promise .then(res => { // 假設 promise 成功 this.data.res = res; // 將 res 的神奇 string 儲存到 data 中 console.log(this.data); }) } } component.init() ```