# Promise 非同步觀念|筆記 by Jiang ###### tags: `Jiang` `Vue新手夏令營` - [Vue 新手夏令營 課程頁面](https://hackmd.io/@dbFY0UD9SUeKmNXhWf01ew/BkJoW-hn_/%2FC05go-8iTSS-nrMwKU22kA) - [:sun_with_face:筆記入口](/2JiZbCPdR0G4p5fNycPmTg) ## Promise 非同步觀念 ![](https://i.imgur.com/GKOqn2H.png) ```jsx // #1 非同步的觀念 基本上取得遠端資料都是 function getData() { setTimeout(() => { console.log('... 已取得遠端資料'); }, 0); } // 請問取得資料的順序為何 const component = { init() { console.log(1); getData(); //非同步行為會被放到最後,會在所有程式碼執行完之後,才會執行非同步行為 console.log(2); } } component.init(); // // 更正確的說法,Promise 是為了解決傳統非同步語法難以建構及管理的問題,如有興趣可搜尋 "callback hell js" // #2 Promise // 在此不需要學習 Promise 的建構方式,僅需要了解如何運用即可 const promiseSetTimeout = (status) => { return new Promise((resolve, reject) => { // 帶入 resolve, reject setTimeout(() => { //非同步狀態 if (status) { resolve('promiseSetTimeout 成功') // Fulfilled --> resolve } else { reject('promiseSetTimeout 失敗') // Rejected --> reject } }, 1000); }) } // #2-1 基礎運用 promiseSetTimeout(true) .then(function(res){ //用.then 去接收 console.log(res); }) // #2-2 串接 promiseSetTimeout(true) .then(function(res){ //用.then 去接收 console.log(1,res); return promiseSetTimeout(true) //繼續取得,用 return }) .then (res =>{ console.log(2,res); }) // #2-3 失敗捕捉 promiseSetTimeout(false) .then(res=>{ console.log(res); }) .catch(err=>{ console.log(err); }) // #2-4 元件運用 const component = { data: {}, init() { console.log(this); promiseSetTimeout(true) .then(res=>{ this.data.res=res; //把資料寫回 data console.log(this.data); }) } } component.init(); // #3 實戰取得遠端資料 // #3-1 // https://github.com/axios/axios axios.get('https://randomuser.me/api/gg') //先弄一個假路徑,要做錯誤示範 .then(res => { console.log(res.data.results); }) .catch(err => { // console.log(err); console.log(err.response); }) // #3-2 記得捕捉錯誤,Axios 錯誤捕捉技巧 // https://randomuser.me/ ``` ![](https://i.imgur.com/SRLKy0O.png)