點燈坊

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

使用 and 對 Future 執行 && 判斷

Sam Xiao's Avatar 2021-06-30

若想對 Future 執行類似 ECMAScript 的 && 判斷,可使用 and

Version

Fluture 14.0.0

Resolved Future

import { pipe } from 'ramda'
import { resolve, fork, and } from 'fluture'
import { error, log } from 'wink-fp'

let data = resolve (1)

let f = pipe (
  and (resolve (2)),
  fork (error) (log)
)

f (data) 

data 為 Resolved Future 時,則回傳另一個 Future (可為 Rejected Future 或 Resolved Future),否則回傳原 Future,此時可使用 and 判斷,類似 ECMAScript 的 &&

and
Future a c -> Future a b -> Future a c
若為 Resolved Future,則回傳新 Future,否則回傳原 Future

  • Future a c:傳入新 Future,可為 Rejected Future 或 Resolved Future
  • Future a b:data 為 Future
  • Future a c:回傳新 Future 或原 Future

and000

Rejected Future

import { pipe } from 'ramda'
import { reject, resolve, fork, and } from 'fluture'
import { error, log } from 'wink-fp'

let data = reject (1)

let f = pipe (
  and (resolve (2)),
  fork (error) (log)
)

f (data) 

data 為 Rejected Future,則直接回傳原 Future。

and001

Railway Oriented Programming

and002

and 支援 Railway Oriented Programming,因為傳入可能是 Rejected Future 或 Resolved Future,因此可能切到 Rejected Track 或 Resolved Track。

Conclusion

  • and 很類似 ECMAScript 的 && operator,但只適用於 Future

Reference

Aldwin Vlasbolm, Functional Alternative to Promises
Fluture, and