處理 RESTful API 的 GET 回傳 Primitive 在實務上一定會碰到,傳統會使用 Promise 處理,事實上 Future 更適合 Point-free。
Version
Vue 3.0.11
Fluture 14.0.0
Future
按下 Get Book
會從 API 獲得 title
。
api/getBook_.js
import axios from 'axios'
import { encaseP } from 'fluture'
export default id => _ => encaseP (axios) (`/book/${id}`)
encaseP
:將axios
轉成回傳 Future 的 function 後,再傳入 url
App.vue
<template lang='pug'>
div
button(@click='onClick') Get Book
div {{ title }}
</template>
<script setup>
import { ref } from 'vue'
import { write } from 'vue3-fp'
import { pipe, map, path } from 'ramda'
import { error } from 'wink-fp'
import { fork, mapRej } from 'fluture'
import getBook from '/src/api/getBook_'
let title = ref ('')
let onClick = pipe (
getBook (1),
map (path (['data', 'title'])),
mapRej (path (['response', 'data', 'error'])),
fork (error) (write (title))
)
</script>
17 行
let onClick = pipe (
getBook (1),
map (path (['data', 'title'])),
mapRej (path (['response', 'data', 'error'])),
fork (error) (write (title))
)
使用 pipe
組合 onClick
:
getBook (1)
:將id
傳入getBook
回傳 Futuremap (path (['data', 'title']))
:在 Resolved Future 內取得data.title
mapRej (path (['response', 'data', 'error']))
:在 Rejected Future 內取得response.date.error
fork (error) (write (title))
:從 Future 內處理 Rejected Future,並從 Resolved Future 內取出資料寫入title
state
Conclusion
- 透過
mapRef
可在pipe
內處理 Rejected Future,不必再如otherwise
需另外組合 function 處理 Rejected Promise