Skip to content

Instantly share code, notes, and snippets.

@airled
Created July 21, 2018 10:06
Show Gist options
  • Save airled/36a8d9c5c6f28aed262fc42dc82e9821 to your computer and use it in GitHub Desktop.
Save airled/36a8d9c5c6f28aed262fc42dc82e9821 to your computer and use it in GitHub Desktop.
Naive promise implementation for Elixir
defmodule Promise do
defstruct functions: []
def new(), do: %Promise{}
def new(func), do: %Promise{functions: [func]}
def then(%Promise{functions: functions} = promise, func) do
Map.put promise, :functions, [func | functions]
end
def run(promise) do
spawn_link fn ->
promise.functions
|> Enum.reverse
|> Enum.reduce(nil, & do_run(&1, &2))
end
end
defp do_run(fun, last_result) do
if :erlang.fun_info(fun)[:arity] == 0 do
fun.()
else
fun.(last_result)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment