问题
I have a pipe like this:
S.pipe([
getRequestFile, // not async
S.chain(saveTemporary), // not async
S.chain(copyImageToPublicPath), // async
S.chain(copyFileToPath), // async
S.chain(someLoggingFunction), // not async
S.chain(sendResponse), // not async
]);
There are 2 async functions in middle of this pipe.
I want to await
for copyImageToPublicPath
and then await
for copyFileToPath
and then continue the normal flow
After some search I found that there is Future.tryP
function for doing async
but how can I use Fluture
in middle of this pipe?
回答1:
It's a matter of lining up the types.
Let's make up some type definitions to use in an example:
foo :: String -> String
bar :: String -> Future Error String
baz :: String -> Array String
Now, let create our program step by step…
// program :: a -> a
const program = S.pipe ([
]);
// program :: String -> String
const program = S.pipe ([
foo, // :: String
]);
// program :: String -> Future Error String
const program = S.pipe ([
foo, // :: String
bar, // :: Future Error String
]);
// program :: String -> Future Error (Array String)
const program = S.pipe ([
foo, // :: String
bar, // :: Future Error String
S.map (baz), // :: Future Error (Array String)
]);
To operate on the b
inside a Future a b
value we use either S.map
or S.chain
.
S.map
can lead to unwanted nesting:
fut :: Future Error String
quux :: String -> Future Error Number
S.map (quux) (fut) :: Future Error (Future Error Number)
We could use S.chain
to avoid this nesting:
fut :: Future Error String
quux :: String -> Future Error Number
S.chain (quux) (fut) :: Future Error Number
It may be helpful to think of S.map
adding to some computation an operation that cannot fail, whereas S.chain
adds a computation that can fail.
来源:https://stackoverflow.com/questions/58697289/execute-fluture-task-in-middle-of-sanctuary-pipe