Axios 為目前 Frontend 最流行的 HTTP Client,回傳為 Promise,可藉由 attemptP
或 encaseP
改回傳 Future。
Version
Fluture 14.0.0
attemptP
import { create, env } from 'sanctuary'
import { attemptP, fork } from 'fluture'
import { env as flutureEnv } from 'fluture-sanctuary-types'
import { log, error } from 'wink-fp'
import axios from 'axios'
let { pipe, map, props } = create ({ checkTypes: true, env: env.concat (flutureEnv) })
let url = 'https://jsonplaceholder.typicode.com/todos/1'
pipe ([
x => attemptP (_ => axios.get (x)),
map (props (['data', 'title'])),
fork (error) (log)
]) (url)
使用 pipe
組合 IIFE:
x => attemptP (_ => axios.get (x))
:將回傳 Promise 的 function 改回傳 Futuremap (props (['data', 'title']))
:從 Future 內取出date.title
fork (error) (log)
:解開 Future
encaseP
import { create, env } from 'sanctuary'
import { encaseP, fork } from 'fluture'
import { env as flutureEnv } from 'fluture-sanctuary-types'
import { log, error } from 'wink-fp'
import axios from 'axios'
let { pipe, map, props } = create ({ checkTypes: true, env: env.concat (flutureEnv) })
let url = 'https://jsonplaceholder.typicode.com/todos/1'
pipe ([
encaseP (axios),
map (props (['data', 'title'])),
fork (error) (log)
]) (url)
使用 pipe
組合 IIFE:
encaseP (axios)
:Axios 預設就是 GET,將axios
轉成回傳 Future 的 functionmap (props (['data', 'title']))
:從 Future 內取出date.title
fork (error) (log)
:解開 Future
Conclusion
attemptP
與encaseP
雖然類似,但其實還是有所差異attemptP
是將回傳 Promise 的 function 改回傳 Future,回傳的是 FutureencaseP
是將回傳 Promise 的 function 轉成回傳 Future 的 function,回傳的是 function