20250222-.then() 裡的 return 是做什麼用的

20250222-.then() 裡的 return 是做什麼用的

.then() 裡的 return 是做什麼用的?

一層一層拆解說明 .then() 中的 return 是在做什麼


🔁 .then() 裡的 return 是做什麼用的?

✅ 簡單說:

每一個 .then() 都可以傳遞資料給「下一個」 .then()
而要傳的資料,就是你在 return 裡寫的東西。


🔍 我們用你的範例來說明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
fetch(url)
.then(response => {
console.log('第一層:取得 response')
return response.json() // ✅ 這裡 return 是要把解析後的 JSON 傳下去
})
.then(data => {
console.log('第二層:取得資料', data)
return data.records // ✅ 把整份資料中的 records 傳下去
})
.then(records => {
console.log('第三層:處理 records', records)
return records.location // ⚠️ 注意!如果 records 是陣列,這樣會錯!
})
.then(locations => {
console.log('第四層:拿到 locations', locations)
})
.catch(error => {
console.error('發生錯誤', error)
})

🧠 一層一層看發生什麼事:

.then() 順序 做的事 return 傳下去的值是什麼?
第一層 拿到 fetch 的 response response.json()(會變成 data
第二層 拿到完整 JSON 資料,名為 data data.records
第三層 拿到 records 陣列 records.location(⚠️小心,records 可能是陣列)
第四層 拿到上一層的 return 值(locations) 印出結果

🔧 小提醒:

1
return data.records

→ 是說:「我只要把整個 records 傳給下一層。」

1
return records.location

→ 這句會錯,如果 records 是一個陣列,因為陣列是沒有 location 屬性的。

你應該這樣寫:

1
return records[0].location

1
return records.map(r => r.location)

✅ 總結:為什麼要用 return

  • return 是為了 將資料傳給下一層.then()
  • 如果不寫 return,下一層 .then() 拿到的是 undefined
  • 每一層都可以「選擇傳什麼資料」給下一層,這就是 Promise chain 的設計