2025-02-21-練習非同步處理與除錯

2025-02-21-練習非同步處理與除錯

✅ 練習目標:

你將會手動寫一段 fetch() 程式,不用 async/await,直接用 .then() 來處理 Promise,並加上 console.log() 做除錯。


🧪 練習範例:用 .then() 查詢 CWA 天氣資料

請貼到 Vue <script setup> 裡試試看這段程式碼(只要你有 API Key):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<script setup>
const apiKey = '你的API金鑰'

function testApiWithThen() {
const url = `https://opendata.cwa.gov.tw/api/v1/rest/datastore/F-C0032-001?Authorization=${apiKey}`

console.log('開始 fetch...') // 除錯點1:確認有執行

fetch(url)
.then(response => {
console.log('取得 response ✔️', response) // 除錯點2
return response.json()
})
.then(data => {
console.log('取得資料 ✅', data) // 除錯點3
})
.catch(error => {
console.error('❌ 發生錯誤', error) // 除錯點4
})
}

// 頁面載入時先測試一次
testApiWithThen()
</script>

🧠 除錯思考方式:

  1. 沒顯示任何 log? → 代表 testApiWithThen() 沒有被呼叫。
  2. .then() 沒執行? → 可能是 fetch 本身錯誤(URL 或網路)。
  3. 資料格式錯誤? → 檢查 .json() 的結構。
  4. CORS 或 API Key 錯誤? → 錯誤會出現在 catch() 裡。

✅ 練習方向

  1. url 改錯一點.catch() 是否有捕捉。
  2. 故意把 apiKey 清掉或打錯 看錯誤訊息。
  3. **印出 data.records**,你就能知道天氣資料是否有拿到。