點燈坊

失くすものさえない今が強くなるチャンスよ

如何使 Axios 回傳 Future ?

Sam Xiao's Avatar 2021-07-25

Axios 為目前 Frontend 最流行的 HTTP Client,回傳為 Promise,可藉由 attemptPencaseP 改回傳 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 改回傳 Future
  • map (props (['data', 'title'])):從 Future 內取出 date.title
  • fork (error) (log):解開 Future

axios000

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 的 function
  • map (props (['data', 'title'])):從 Future 內取出 date.title
  • fork (error) (log):解開 Future

axios001

Conclusion

  • attemptPencaseP 雖然類似,但其實還是有所差異
  • attemptP 是將回傳 Promise 的 function 改回傳 Future,回傳的是 Future
  • encaseP 是將回傳 Promise 的 function 轉成回傳 Future 的 function,回傳的是 function

Reference

Fluture, attemptP
Fluture, encaseP