如何让 Either Monads 知道异步函数(Promises/Future)

How to make Either Monads be aware of of Async functions(Promises/Future)

我正在尝试使用 Either Monad 来传输我的数据,问题是我不知道如何让我的 Monad 知道异步操作

这是我的

let processData = Either.either(_sendError, _sendResponse)

processData(_getDataGeneric(queryResult)
    .chain(_findDevice)
    .chain(_processRequest)
);

queryResult 是我从数据库本身获取的结果。

问题是获取结果只在管道的中间。 我要的是这个

ValidateUserInput -> GetDataFromDB -> ProcessData

processAll(_fetchFromDB(userId)
    .getDataGeneric
    .chain(_findDevice)
    .chain(_processRequest))


//_fetchFromDB , Mongoose Query
 function _fetchFromDB(userId){
        return myModel.findOne({id:userId}).exec()
                                  .then(function(result){
                                     return Right(result)
                                }).catch((err)=>Left(err))
  }

如果数据库的结果有效,它将return一个右实例,如果有任何错误,它将return左

问题是这个操作是异步的,我不确定如何让我的 Either Monad 处理它。

关于如何让我的 Monad 在其操作中意识到 Promises 的任何想法?

如您所见,Either类型只能表示已经实现的值,而异步操作表示可能在未来评估的东西。

A Promise 已经通过表示错误值和成功值的可能性结合了 Either 的行为。它还通过允许 then 到 return 另一个 Promise 实例来捕获单子式操作链接的行为。

但是,如果您对类似于 Promise 的东西感兴趣,它的行为更接近于 Either(并且还遵循 Fantasy Land spec) then you might like to look at one of the Future implementations such as Fluture

例如

import Future from 'fluture';

const processAll = Future.fork(_sendError, _sendResponse);

const _fetchFromDB =
  Future.fromPromise(userId => myModel.findOne({ id: userId }).exec())

processAll(_fetchFromDB(userId)
  .chain(getDataGeneric)
  .chain(_findDevice)
  .chain(_processRequest))