问题描述
我正在尝试使用Monad来通过管道传输数据,问题是我无法弄清楚如何使Monad知道异步操作
I am trying to use Either Monad to pipe my data through, the problem is that I can't figure out how to make my Monad to be aware of the operation that is async
这是我所拥有的
let processData = Either.either(_sendError, _sendResponse)
processData(_getDataGeneric(queryResult)
.chain(_findDevice)
.chain(_processRequest)
);
queryResult是我从数据库本身获取的.
queryResult is what I fetch from the database itself.
问题在于,获取结果仅在管道的中间.我想要的是这个
the problem is that fetching the result is only in the middle of the pipeline.what I want is this
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))
}
如果DB中的结果有效,它将返回Right实例,并且如果有任何错误,它将返回Left
if result is valid from DB,it will return an Right instance, and if there is any sort of error, it will return Left
问题是此操作是异步的,我不确定如何让我的Monad处理和处理它.
the problem is that this operation is Async, and i am not sure how to get my Either Monad to handle it and process it.
关于如何使我的Monad意识到其运行中的承诺的任何想法吗?
Any ideas on how to make my Monad aware of Promises in its operation?
推荐答案
如您所见,任一
类型只能表示已经实现的值,而异步操作表示的是将来可能会评估.
As you're seeing, an Either
type can only represent values that have already been realised, while the asynchronous operation represents something that may be evaluated in the future.
一个 Promise
已经通过表示错误和成功值的可能性,结合了 Either
的行为.通过允许 then
返回另一个 Promise
实例,它还捕获了Monadic式操作链的行为.
A Promise
already combines the behaviour of an Either
, by representing the possibility of both error and successful values. It also captures the behaviour of monadic-style chaining of operations by allowing then
to return another Promise
instance.
但是,如果您对类似于 Promise
的东西感兴趣,该行为与 Either
更为接近(并且遵循幻想土地规范),那么您可能想看看 Future
的一种实现,例如 Fluture
If however you're interested in something similar to a Promise
that behaves more closely to an Either
(and also follows the 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))
这篇关于如何使两个Monad都了解异步功能(承诺/未来)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!