# Promise 非同步觀念 (3) ###### tags: `JavaScript` 2022.2028 ## 介紹   此節是為了銜接Axios串接API,所進行的概念講解,Axios是使用Promise非同步方式取得其他網站資料。   以下將用簡單Promise程式演示運作流程: ``` //#########Promise模擬Axios取資料流程######### const promiseSetTmeout = (status) =>{ return new Promise((resolve,reject) =>{ setTimeout(()=>{ if (status){ resolve('promiseSetTimeout 成功'); } else{ reject('promiseSetTimeout 失敗'); } },0); }) } //########################################## ``` * 一般取得資料 ``` const 網址 = true; //假設給予網址有資料 promiseSetTmeout(網址) .then(res=>console.log(res)) .catch(err=>console.log(err)) ``` * 一次取得多網頁資料(串接) ``` const 網址1 = true; const 網址2 = false; //假設從網址1中抓取到網址2 promiseSetTmeout(網址1) .then(res=>{ console.log(1,res); return promiseSetTmeout(網址2) }) .then(res=>{ console.log(2,res); }) .catch(err=>{ console.log(err); }) ``` * 將得到資料寫入本地數據 ``` const 網址 = true; const component = { data: {}, init(){ promiseSetTmeout(網址) .then(res=>{ this.data.res = res; console.log(this.data); }) .catch(err=>console.log(err)) } } component.init(); ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up