Implemented in https://github.com/algesten/fnuc/blob/master/src/fnuc.coffee#L202
This example shows how plift
can help to treat functions dealing with promises as regular functions.
N.B. This code is a "handler" it is not intended to be side effect free.
userToDevices
is a function looking up devices from a user id in a database. It returns a promise for the result.ex.publish
publishes the result over AMQP. Our wrapper makes this also return a promise.
However, when writing the test code for these functions, we can simply ignore that there are any promises involved. Both ex
and userToDevices
can be mocked to return immediate function returns and we can still be confident it works for promises.
{firstfn, map, mixin, plift, sequence} = require 'fnuc'
Q = require 'q'
ppipe = (fs...) -> sequence (map(plift) fs)... # sequence of plifted funcs
# mixin the message into the device specification
deviceWithMessage = (message) -> (d) -> mixin d, {message}
# check if given array has any promise
anyPromise = firstfn Q.isPromiseAlike
# wait for all promises in array to resolve or just return array
waitFor = (todo) -> if anyPromise(todo) then Q.all(todo) else todo
# {user:<userid>, message:{title:<title>, body:<body>}}
module.exports = (ex, userToDevices) ->
# publish the message to exchange
publish = (m) -> ex.publish 'device', m
(user, message) ->
ppipe(
userToDevices,
map(deviceWithMessage(message)),
map(publish),
waitFor
) user