Created
July 21, 2018 10:06
-
-
Save airled/36a8d9c5c6f28aed262fc42dc82e9821 to your computer and use it in GitHub Desktop.
Naive promise implementation for Elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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